Chinaunix首页 | 论坛 | 博客
  • 博客访问: 15968
  • 博文数量: 9
  • 博客积分: 411
  • 博客等级: 一等列兵
  • 技术积分: 120
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-13 22:50
文章分类

全部博文(9)

文章存档

2011年(2)

2010年(7)

我的朋友

分类: C/C++

2010-12-26 21:56:10

今天自己写了一个myls。主要完成的是,列出指定目录下的文件名及类型。实现过程中主要使用了opendir,closedir,readdir,lstat函数。#include #include #include #include #include #include void printf_filetype(struct stat *filestat){        if (S_ISREG(filestat->st_mode)){                printf("-");                return ;        }        if (S_ISDIR(filestat->st_mode)){                printf("d");                return ;        }        if (S_ISCHR(filestat->st_mode)){                printf("c");                return ;        }        if (S_ISBLK(filestat->st_mode)){                printf("b");                return ;        }        if (S_ISFIFO(filestat->st_mode)){                printf("f");                return ;        }        if (S_ISLNK(filestat->st_mode)){                printf("l");                return ;        }}void printf_fileusr(struct stat *filestat){        printf("%d", filestat->st_uid);        return ;}int main(int argc, char **argv){        DIR *fddir;//注意这里定义了一个指针类型。        struct dirent *rddir;//这里也定义了一个指针类型。因为它出现在函数的返回值中。        int ret;        struct stat statbuf;//这里却定义的是结构体。因为它会出现在函数的参数中,而并不是出现在函数的返回值当中。        char buf[256];        if (argc != 2){                printf("argument fault...\n");                return 1;        }        fddir = opendir(argv[1]);//函数返回一个指针指向DIR类型的结构,函数肯定在实现的过程中分配了这样的一个空间。所以这个空间会在closedir时候释放掉。        if (fddir == NULL){                perror("opendri");                return 1;        }        while(1){                rddir = readdir(fddir);//注意函数返回了一个指向struct dirent 结构体类型的指针。所以函数在实现的过程中也分配了内存空间,但这个空间似乎没有函数来释放。???                if (NULL == rddir){                        if (errno == EBADF){                                perror("readdir");                                return 1;                        }                        break;                }                sprintf(buf, "%s/%s", argv[1], rddir->d_name);//第一个%s表示的是rddir指向的文件所在的路径。第二个%s表示的当前rddir指向的文件名。                ret = lstat(buf, &statbuf);//                if (ret == -1){                        perror("lstat");                        return 1;                }                printf_filetype(&statbuf);                putchar(' ');                printf_fileusr(&statbuf);                putchar(' ');                printf("%s\n", rddir->d_name);        }        closedir(fddir);//注意不要忘记closedir。        return 0;}
阅读(514) | 评论(1) | 转发(0) |
0

上一篇:mycpy

下一篇:myglob

给主人留下些什么吧!~~

chinaunix网友2011-01-04 09:04:56

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com