【问题标题】:how can i get all file name in a directory without getting "." and ".." in C如何在不获取“。”的情况下获取目录中的所有文件名和 C 中的“..”
【发布时间】:2013-08-28 00:52:00
【问题描述】:

我正在使用 Linux 系统。

 DIR *dir;
  struct dirent *ent;
  while ((ent = readdir (dir)) != NULL) {           
    printf ("%s\n", ent->d_name);
  }

我得到了 "."".." 和一些文件名。 我怎样才能摆脱"."".."? 我需要这些文件名以进行进一步处理。 ent->d_name是什么类型的??是字符串还是字符?

【问题讨论】:

  • stackoverflow.com/questions/12991334/… 。如果d_name 是一个字符,那么使用%s 打印它将是未定义的行为(更不用说使用一个字符来存储整个文件名需要一些惊人的数据压缩算法)。
  • "ent->d_name 的类型是什么??是字符串还是字符?" - 你读过文档吗?

标签: c linux


【解决方案1】:

阅读 readdir 的手册页,得到这个:

struct dirent {
               ino_t          d_ino;       /* inode number */
               off_t          d_off;       /* offset to the next dirent */
               unsigned short d_reclen;    /* length of this record */
               unsigned char  d_type;      /* type of file; not supported
                                              by all file system types */
               char           d_name[256]; /* filename */
           };

所以ent->d_name 是一个字符数组。当然,您可以将其用作字符串。

摆脱"."".."

while ((ent = readdir (dir)) != NULL) {  
if (strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "..") != 0 )
    printf ("%s\n", ent->d_name);
  }

更新

生成的ent 包含文件名和文件夹名。如果不需要文件夹名称,最好检查ent->d_type字段和if(ent->d_type == DT_DIR)

【讨论】:

  • 当然字符串类型无论如何都不存在于 C 中(仅在 C++ 中),因此所有字符串实际上只是一个字符数组。
  • @UltimateGobblement 完全正确。
【解决方案2】:

使用strcmp

while ((ent = readdir (dir)) != NULL) {  
if (strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "..") != 0)         
    //printf ("%s\n", ent->d_name);
  }

【讨论】:

    猜你喜欢
    • 2012-04-18
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多