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