如何从C中的目录中检索文件名和子目录名?

时间:2010-10-28 16:21:22

标签: c file file-io directory

好的我有这样的事情:

struct dirent *dp;
DIR *dir;
char fullname[MAXPATHLEN];
char** tmp_paths = argv[1]; //Not the exact code but you get the idea.

...

while ((dp = readdir(dir)) != NULL)
{
    struct stat stat_buffer;

    sprintf(fullname, "%s/%s", *tmp_paths, dp->d_name);

    if (stat(fullname, &stat_buffer) != 0)
        perror(opts.programname);

    /* Processing files */
    if (S_ISDIR(stat_buffer.st_mode))
    {
        nSubdirs++;
        DIRECTORYINFO* subd = malloc(BUFSIZ);
    }

    /* Processing subdirs */
    if (S_ISREG(stat_buffer.st_mode))
    {
        nFiles++;
        FILEINFO *f = malloc(BUFSIZ);
    }
}

如何将文件名和子目录名称读入我自己的结构DIRECTORYINFO和FILEINFO?我已经通过stat.h并且没有找到任何有用的东西。

3 个答案:

答案 0 :(得分:1)

在UNIX世界中,名称不是文件的一部分,因此stat(2)无法检索有关它的信息。但是在您的代码中,您的名称为dp->d_name,因此您可以将该字符串复制到您自己的数据结构中。这应该很简单。

如果这不是你的问题,我不明白这个问题。

答案 1 :(得分:0)

查看this问题及其答案。您可能想要使用dirent->d_name

答案 2 :(得分:0)

Glob是你的朋友

glob()函数根据shell使用的规则搜索匹配模式的所有路径名

/* Sample Code */
#include <glob.h>    
glob_t data;
glob("*", 0, NULL, &data ); /* Here "*" says to match all files of the current dir */
for(int i=0; i<data.gl_pathc; i++)
{
    /* Printing all the path names,Just for illustration */
    printf( "%s\n", data.gl_pathv[i] );
}
/* To split into DIRINFO and FILEINFO, stat(2) should be made use of */
globfree( &data ); /* free the data structure */

要获得更多详细信息,您可以随时使用unix man page

  

man glob