Kat*_*tie 4 c unix char dirent.h
我想在给定目录中只获取*.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;
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能在纯unixs c中做到这一点?
Fre*_*Foo 10
首先,Unix没有文件扩展的概念,所以没有extension
成员struct dirent
.其次,你无法比较字符串==
.你可以使用类似的东西
bool has_txt_extension(char const *name)
{
size_t len = strlen(name);
return len > 4 && strcmp(name + len - 4, ".txt") == 0;
}
Run Code Online (Sandbox Code Playgroud)
该> 4
部分确保文件名.txt
不匹配.
(bool
从中获取<stdbool.h>
.)
您可以使用glob()
函数调用.更多信息使用您最喜欢的搜索引擎,Linux手册页或此处.
#include <glob.h>
#include <stdio.h>
int main(int argc, char **argv) {
const char *pattern = "./*.txt";
glob_t pglob;
glob(pattern, GLOB_ERR, NULL, &pglob);
printf("Found %d matches\n", pglob.gl_pathc);
printf("First match: %s\n", pglob.gl_pathv[0]);
globfree(&pglob);
return 0;
}
Run Code Online (Sandbox Code Playgroud)