我只想获取给定目录中 *.txt 文件的名称,如下所示:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <dirent.h>
int main(int argc, char **argv)
{
char *dirFilename = "dir";
DIR *directory = NULL;
directory = opendir (dirFilename);
if(directory == NULL)
return -1;
struct dirent *ent;
while ((ent = readdir (directory)) != NULL)
{
if(ent->d_name.extension == "txt")
printf ("%s\n", ent->d_name);
}
if(closedir(directory) < 0)
return -1;
return 0;
}
我如何在纯 unix c 中执行此操作?
最佳答案
首先,Unix 没有文件扩展名的概念,所以没有 extension
成员(member) struct dirent
.其次,您不能将字符串与 ==
进行比较。 .你可以使用类似的东西
bool has_txt_extension(char const *name)
{
size_t len = strlen(name);
return len > 4 && strcmp(name + len - 4, ".txt") == 0;
}
> 4
部分确保文件名 .txt
不匹配。
(从 bool
获得 <stdbool.h>
。)
关于c - 我怎样才能只从c目录中获取txt文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12976733/