系统调用
#include <dirent.h>
DIR *opendir(const char *name);
struct dirent *readdir(DIR *dirp);
代码实例
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <errno.h>
#include <dirent.h>
void list_files(const char * dir_path);
int main(int argc, char * argv[])
{
if(argc > 1 && strcmp(argv[1], "--help") == 0)
{
printf("Usage: %s [dir...]\n", argv[0]);
return EXIT_SUCCESS;
}
if(argc == 1)
list_files(".");
else
for(int i = 1; i < argc; i++)
list_files(argv[i]);
return EXIT_SUCCESS;
}
void list_files(const char * dir_path)
{
DIR * dirp;
struct dirent * dp;
bool is_current;
is_current = strcmp(dir_path, ".") == 0;
if((dirp = opendir(dir_path)) == NULL)
{
perror("opendir");
exit(EXIT_FAILURE);
}
while(true)
{
errno = 0;
if((dp = readdir(dirp)) == NULL)
break;
if(strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0)
continue;
if(!is_current)
{
printf("%s/", dir_path);
}
printf("%s\n", dp->d_name);
}
}