APUE_1UNIXSystemOverview Figure1.3ListAllTheFilesInADirectory

HT`2PQ6P77C`$$BBGEMK6EO

)C@2J[96FQ(IU8LRV%ESM9G

F7R{){_Y3WYUPI6X8J~X{IF

KW6RLP2WDJ$KWCH0I$]}1%A

]I]BUD79L~ZQKIDMROXIQMX

GRN74NG(792Z{7`0O]6_4ID

7TO7U{WFMNV`X6PHF7CRIZL

// 1.3ListAllTheFilesInADirectory.cpp
#include <dirent.h>

#include "../apuesunyj.h"

int main(int argc, char *argv[])
{
	DIR* dp;
	struct dirent* dirp;
	if (2 != argc)
	{
		err_quit("usage: ls directory_name");
	}
	if ((dp = opendir(argv[1])) == NULL)
	{
		err_sys("can’t open %s", argv[1]);
	}
	while ((dirp = readdir(dp)) != NULL)
	{
		printf("%s
", dirp->d_name);
	}
	closedir(dp);
	return 0;
}

OD~(JQ7X(LW8UY)`0ZE7EJB

Q%8U%6VPMJV_{_PWEF[2H$U

 1 // error.cpp
 2 #include "apuesunyj.h"
 3 
 4 int64_t const MAXLINE = 4096; // max line length
 5 /*
 6  *  * Print a message and return to caller.
 7  *   * Caller specifies "errnoflag".
 8  *    */
 9 static void err_doit(int errnoflag, int error, const char *fmt, va_list ap)
10 {
11     char buf[MAXLINE];
12 
13     vsnprintf(buf, MAXLINE, fmt, ap);
14     if (errnoflag)
15         snprintf(buf + strlen(buf), MAXLINE - strlen(buf), ": %s", strerror(
16                     error));
17     strcat(buf, "
");
18     fflush(stdout);/* in case stdout and stderr are the same */
19     fputs(buf, stderr);
20     fflush(NULL);/* flushes all stdio output streams */
21 }
22 
23 /*
24  *  * Fatal error unrelated to a system call.
25  *   * Print a message and terminate.
26  *    */
27 void err_quit(const char *fmt, ...)
28 {
29     va_list ap;
30 
31     va_start(ap, fmt);
32     err_doit(0, 0, fmt, ap);
33     va_end(ap);
34     exit(1) ; // process terminate, not just like return, totally different
35 }
36 
37 /*
38  *  * Fatal error related to a system call.
39  *   * Print a message and terminate.
40  *    */
41 void err_sys(const char *fmt, ...)
42 {
43     va_list ap;
44 
45     va_start(ap, fmt);
46     err_doit(1, errno, fmt, ap);
47     va_end(ap);
48     exit(1) ;
49 }
 1 // apuesunyj.h
 2 #ifndef APUE_SUNYJ
 3 #define APUE_SUNYJ
 4 
 5 #include <errno.h>
 6 #include <stdio.h>
 7 #include <string.h>
 8 #include <stdarg.h>
 9 #include <stdlib.h>
10 #include <stdint.h>
11 #include <unistd.h>
12 
13 void err_quit(const char *fmt, ...);
14 void err_sys(const char *fmt, ...);
15 
16 
17 #endif

IMG_1169

IMG_1170

IMG_1171IMG_1172IMG_1173IMG_1176IMG_1177IMG_1178IMG_1179

IMG_1180IMG_1208IMG_1210IMG_1211IMG_1212IMG_1213IMG_1214

原文地址:https://www.cnblogs.com/sunyongjie1984/p/4284728.html