簡體   English   中英

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

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

我正在使用Linux系統。

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

我得到"." ".."和一些文件名。 我如何擺脫"." ".." 我需要這些文件名以進行進一步處理。 ent->d_name的類型是什么? 是字符串還是char?

閱讀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是一個char數組。 當然,您可以將其用作字符串。

擺脫"." ".."

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

更新資料

生成的ent包含文件名和文件夾名。 如果不需要文件夾名稱,最好使用if(ent->d_type == DT_DIR)檢查ent->d_type字段。

使用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