[英]How to list all files of a directory recursively in c
这是一个递归列出目录下所有文件的ac程序,因此它可以列出c:驱动器中的所有文件。
上面的程序运行良好,但我已经尝试了 5 天,如果不使用函数(只有 main ,而不是 main 和另一个函数(listFilesRecursively)),我就无法让它工作
#include <stdio.h>
#include <string.h>
#include <dirent.h>
void listFilesRecursively(char *path);
int main()
{
// Directory path to list files
char path[100];
// Input path from user
strcpy(path , "c://");
listFilesRecursively(path);
return 0;
}
/**
* Lists all files and sub-directories recursively
* considering path as base path.
*/
void listFilesRecursively(char *basePath)
{
char path[1000];
struct dirent *dp;
DIR *dir = opendir(basePath);
// Unable to open directory stream
if (!dir)
return;
while ((dp = readdir(dir)) != NULL)
{
if (strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0)
{
printf("%s\n", dp->d_name);
// Construct new path from our base path
strcpy(path, basePath);
strcat(path, "/");
strcat(path, dp->d_name);
listFilesRecursively(path);
}
}
closedir(dir);
}
谢谢 :)
我一辈子都想不通为什么有人想通过递归调用main()
来枚举目录。 但是,由于我无法抗拒一个毫无意义的挑战,这里有一个版本可以。 我是否因“十分钟最无用的浪费”而获奖? ;)
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <errno.h>
#include <stdlib.h>
int main (int argc, char **argv)
{
const char *path;
if (argc != 2) path = "/etc"; /* Set starting directory, if not passed */
else
path = argv[1];
DIR *dir = opendir (path);
if (dir)
{
struct dirent *dp;
while ((dp = readdir(dir)) != NULL)
{
if (dp->d_name[0] != '.')
{
char *fullpath = malloc (strlen (path) + strlen (dp->d_name) + 2);
strcpy (fullpath, path);
strcat (fullpath, "/");
strcat (fullpath, dp->d_name);
if (dp->d_type == DT_DIR)
{
char **new_argv = malloc (2 * sizeof (char *));
new_argv[0] = argv[0];
new_argv[1] = fullpath;
main (2, new_argv);
free (new_argv);
}
else
printf ("%s\n", fullpath);
free (fullpath);
}
}
closedir(dir);
}
else
fprintf (stderr, "Can't open dir %s: %s", path, strerror (errno));
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.