如何检查文件名是否是 C 中的目录?
How do I check if file name is a directory or not in C?
我正在使用 if(strstr(dir->d_name, ".") == NULL && strstr(dir->d_name, "..")
检查它是否是 directory/subdirectory,但这仍然打印出一些不是目录的文件...我正在使用直接结构和 DIR。
如果您使用 Linux,您可以使用 getdents
which include entry type. Otherwise you'll probably have to use stat
/lstat
来获取每个项目的类型信息。
strstr
在另一个字符串中搜索子字符串,因此它将 return 匹配每个 name 包含单个(嗯,或双)期间。
您可能打算使用 strcmp
:
if (strcmp(dir->d_name, ".") && strcmp(dir->d_name, ".."))
.. not one of the default root folders ..
在此之前或之后,您可以检查它是否是一个文件夹:
if (dir->d_type == DT_DIR)
..
或使用stat
。 (请注意,某些文件系统类型可能不支持 d_type
。)
就个人而言,我喜欢 stat() 和 fstat()。然后,您使用 S_ISDIR(m) 等宏查看输出的 st_mode 字段。
我正在使用 if(strstr(dir->d_name, ".") == NULL && strstr(dir->d_name, "..")
检查它是否是 directory/subdirectory,但这仍然打印出一些不是目录的文件...我正在使用直接结构和 DIR。
如果您使用 Linux,您可以使用 getdents
which include entry type. Otherwise you'll probably have to use stat
/lstat
来获取每个项目的类型信息。
strstr
在另一个字符串中搜索子字符串,因此它将 return 匹配每个 name 包含单个(嗯,或双)期间。
您可能打算使用 strcmp
:
if (strcmp(dir->d_name, ".") && strcmp(dir->d_name, ".."))
.. not one of the default root folders ..
在此之前或之后,您可以检查它是否是一个文件夹:
if (dir->d_type == DT_DIR)
..
或使用stat
。 (请注意,某些文件系统类型可能不支持 d_type
。)
就个人而言,我喜欢 stat() 和 fstat()。然后,您使用 S_ISDIR(m) 等宏查看输出的 st_mode 字段。