本程序主要练习使用函数opendir,readdir,closedir对目录进行处理,实现读取目录中所有文件的功能。函数清单如下:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
int main(int argc,char *argv[])
{
DIR *dp;
struct dirent *dirp;
if(argc != 2)
{
perror("the number of arguments is wrong!");
exit(1);
}
if((dp = opendir(argv[1])) == NULL)
{
printf("Can't open %s\n",argv[1]);
exit(1);
}
while((dirp = readdir(dp)) != NULL)
{
printf("%s\n",dirp->d_name);
}
closedir(dp);
exit(0);
}
|
编译源文件:
gcc -o listfile listfile.c
执行文件:
./listfile ~/eagle
输出结果:
Can't open /home/longmenyu/eagle
执行文件:
./listfile ~/test/code
输出结果:
listfile
hello
mythread
.
..
main_function
执行文件:
./listfile /home /home/longmenyu/test
输出结果:
the number of arguments is wrong!: Success
阅读(874) | 评论(1) | 转发(0) |