简体   繁体   English

我如何在C中获取目录中的所有文件名而又不获取“。”和“ ..”

[英]how can i get all file name in a directory without getting “.” and “..” in C

I am working with Linux system. 我正在使用Linux系统。

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

I get "." 我得到"." , ".." and some file names as a result. ".."和一些文件名。 How can I get rid of "." 我如何摆脱"." and ".." ? ".." I need those file names for further process. 我需要这些文件名以进行进一步处理。 What's the type of ent->d_name ?? ent->d_name的类型是什么? Is it a string or char? 是字符串还是char?

Read the man page of readdir, get this: 阅读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 */
           };

So ent->d_name is a char array. 所以ent->d_name是一个char数组。 You could use it as a string, of course. 当然,您可以将其用作字符串。

To get rid of "." 摆脱"." and ".." : ".."

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

Update 更新资料

The resulting ent contains file names and file folder names. 生成的ent包含文件名和文件夹名。 If folder names are not needed, it is better to check ent->d_type field with if(ent->d_type == DT_DIR) . 如果不需要文件夹名称,最好使用if(ent->d_type == DT_DIR)检查ent->d_type字段。

Use strcmp : 使用strcmp

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM