最近在看着本书,感觉不错,今天先拿第一个程式练练,这是打印一个文档下的文档的程式,是第一个程式,比较简单,代码如下:

#include "err.h"

            #include <dirent.h>

            int main(int argc, char* argv[])

            {

            DIR *dp;

            struct dirent *dirp;

            if(argc != 2)

            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\n", dirp->d_name);

            close(dp);

            return 0;

            }

这里用到的err.h是个自己编写的头文档,因为这本书中用到的源文档都早apue上,我自己写了一部分,这个err_quit其中应该是变参数的,但是我还不会写,明天看看,现在太晚了,头文档如下:

#include <stdio.h>

            void err_quit(const char *fmt)

            {

            printf( "%s\n", fmt);

            }

            void err_sys(const char *f, const char *s)

            {

            printf("%s %s\n", f, s);

            }

打印一个输出结果如下:

[root@localhost apue]# ./a.out .

            .

            ..

            apue

            apue.h

            rk1.c~

            err.h

            a.out

            fig1.3.c

            rk1.c

这个程式有很多需要注意的地方,虽然代码很少,但是很典型。