一个C文件:listdir.c,一个Makefile文件.
//file: listdir.c
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#ifdef __cplusplus
extern "C" {
#endif
#define MAX_PATH_LEN 256
int main(void)
{
char path[MAX_PATH_LEN] = {0};
DIR *dir = NULL;
struct dirent *ptr = NULL;
printf("Please input the path:");
scanf("%s", path);
if( NULL == (dir = opendir(path)) )
{
switch(errno)
{
case EACCES:
{
printf("No premium to access %s ...\n", path);
/*Add code here*/
}
break;
case ENFILE:
{
printf("Up to the number of system can open ...\n");
/*Add code here*/
}
break;
case EMFILE:
{
printf("Up to the number of process can open ...\n");
/*Add code here*/
}
break;
case ENOTDIR:
{
printf("%s is not a real dir ...\n", path);
/*Add code here*/
}
break;
case ENOENT:
{
printf("%s not exist ...\n", path);
/*Add code here*/
}
break;
default :
{
printf("Error undefined ...");
}
}break;
goto exit_dir;
}
while( NULL != (ptr = readdir(dir)) )
{
/*file:8, dir:4*/
switch(ptr->d_type)
{
case 8:
{
printf("File:%s\n", ptr->d_name);
}
break;
case 4:
{
printf("Dir:%s\n", ptr->d_name);
}
break;
default :
{
printf("Neither a file nor a dir ...");
}
break;
}
}
closedir(dir);
return 0;
exit_dir:
closedir(dir);
return -1;
}
#ifdef __cplusplus
};
#endif
//file: Makefile
listdir : listdir.o
gcc -o listdir listdir.o
listdir.o : listdir.c
gcc -g -Wall -c listdir.c
clean:
rm -rf listdir.o listdir
使用方法:make后运行listdir,程序提示输入要遍历的路径,输入路径后回车就可以。