【问题标题】:How to retrieve file names and subdirectory names from a directory in C?如何从 C 中的目录中检索文件名和子目录名?
【发布时间】:2011-05-01 23:49:10
【问题描述】:

好的,我有这样的事情:

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 并没有发现任何有用的东西。

【问题讨论】:

  • 目录是 OS 功能,不是 C 的一部分。您必须指定平台。

标签: c file file-io directory


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 是的,谢谢。只是我的印象是 d_name 只适用于目录。
    • 对于 UNIX 中的 struct 类型,字段以常见的 something 和下划线为前缀是很常见的。例如struct direntd_*struct statst_*struct timetm_*
    【解决方案3】:

    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 ma​​n page

    人球

    【讨论】:

      猜你喜欢
      • 2013-09-20
      • 1970-01-01
      • 2011-09-09
      • 2021-01-25
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多