【问题标题】:C program to print directory names in a directory and exclude current directory and parent directory [duplicate]C程序打印目录中的目录名称并排除当前目录和父目录[重复]
【发布时间】:2016-07-06 17:25:33
【问题描述】:

我有一个程序,通过检查 d_type == DT_DIR 来打印出特定目录中列出的所有目录

程序运行,但也打印出父目录..和当前目录.

我尝试设置一个 if 语句来检查 d_name != ".." or ".",但它仍然打印父目录和当前目录

这是我添加了 if 语句的代码

 directory = opendir("/home/user/adirectory");

    if(directory != NULL)
    {
        while(entry = readdir(directory)) {
            if(entry->d_type == DT_DIR && entry->d_name != ".." && entry->d_name != ".")
                printf("%s\n", entry->d_name);
        }


    }

不幸的是,这是输出,其中 dir2adirectory

中的目录
..
dir2
.

我想要一个只显示这个目录的输出,没有点或两个点

dir2

【问题讨论】:

  • 使用 strncmp() 代替 strcmp() 使代码更安全。
  • 列出目录的另一种方法是使用:int listDir(const char *dirpath) { glob_t gdir = { 0, }; regex_t r1 = { 0, }; regex_t r2 = { 0, }; const char p1[] = "\(^\[\.\]\{1,2\}\/\)"; // RE for filtering const char p2[] = "\(\/$\)"; // RE for inclusion char pwd[PATH_MAX + 1] = { 0, }; getcwd(…); chdir(…); result = regncomp(&1, p1, strlen(p1), REG_EXTENDED); result = regncomp(&2, p2, strlen(p2), REG_EXTENDED); // STUFF code posted in another comment below regfree(&r1); regfree(&r2); chdir(…); return 0; }
  • 要塞进上述评论的代码:if ((glob(".*", (…|GLOB_MARK), NULL, &gdir) == 0) && (glob("*", (…|GLOB_MARK | GLOB_APPEND), NULL, &gdir) == 0)) { for (int i = 0; i < gdir.gl_pathc; i ++) { char *ps = gdir.gl_pathv[i]; int sz = strlen(gdir.gl_pathv[i]; if ((REG_NOMATCH == regnexec(&reg1, ps, sz), 0, NULL, 0)) && (REG_NOMATCH != regnexec(&reg2, ps, sz), 0, NULL, 0))) printf(" [%02d] %s\n", (i + 1), ps); } globfree(&gdir); }
  • 请注意,我在上面的 cmets/code 中进行了一些编辑,例如“...”,因此您可能需要相应地更改它们才能使其正常工作。

标签: c linux directory dirent.h


【解决方案1】:

您的代码的问题是您在字符串上使用!= 运算符,这在C 中NOT 有效。您必须使用strcmp 函数来比较两个字符串。如果你不知道如何使用strcmp 函数,那么你可以谷歌一下。这就是问题所在,

    if(entry->d_type == DT_DIR && entry->d_name != ".." && entry->d_name != ".")

This 可能会有所帮助。

【讨论】:

    【解决方案2】:

    C 中的字符串比较可以使用 strcmp 函数来完成。您不能使用 = 符号比较字符串。下面是用 strcmp 更新的代码。

    directory = opendir("/home/user/adirectory");
    
        if(directory != NULL)
        {
            while(entry = readdir(directory)) {
                if(entry->d_type == DT_DIR && strcmp(entry->d_name,"..")!=0 && strcmp(entry->d_name, ".")!=0)
                    printf("%s\n", entry->d_name);
            }
    
    
        } 
    

    【讨论】:

      【解决方案3】:

      您需要使用strcmp。见this post

      【讨论】:

      • 所以它会像strcmp(entry->d_name, "..") != 0 ?
      • 对我的问题是的,因为它有效
      猜你喜欢
      • 2015-08-22
      • 2018-06-25
      • 1970-01-01
      • 2012-01-29
      • 1970-01-01
      • 1970-01-01
      • 2018-03-01
      • 2011-07-05
      相关资源
      最近更新 更多