[英]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.