gpt4 book ai didi

c - 如何使用c程序检查子目录是否包含文本文件

转载 作者:行者123 更新时间:2023-11-30 15:09:36 26 4
gpt4 key购买 nike

我有一个目录 A,其中有子目录 aa、bb、cc、dd、ee、ff。每个子目录都有多个.txt、.bin、.dat 文件。我想要做的是,检查每个子目录是否包含文本文件,如果是则返回子目录名称。

下面的c脚本列出了子目录,但请协助检查子目录中是否有txt文件。

我正在尝试在 Windows 7-Visual Studio 2010 中执行此操作

#include <dirent.h> 
#include <stdio.h>
int main(void)
{
DIR *d;
DIR *f;
struct dirent *dir;
d = opendir("C:\\Users\\xp\\Desktop\\Star1");
if (d) {
while ((dir = readdir(d)) != NULL) {
if (dir->d_name[0] != '.') {
f=opendir(dir->d_name);
if (strstr(dir->d_name , ".txt")) {
printf("%s\n", dir->d_name);
}
}
}
closedir(d);
}

return(0);
}

最佳答案

您可以使用标志。如果您发现文件“.txt”结尾,则设置标志并退出循环。循环结束后,您检查标志。

<小时/>

一种检查字符串是否以特定子字符串结尾的方法:

static const char string_to_find[] = ".txt";

...

// First make sure the filename is long enough to fit the name-suffix
if (strlen(dir->d_name) > strlen(string_to_find))
{
// +strlen(dir->d_name) to get a pointer to the end of dir->d_name
// -strlen(string_to_find) to get a pointer to where the suffix should start
if (strcmp(dir->d_name + strlen(dir->d_name) - strlen(string_to_find),
string_to_find) == 0)
{
// File-name ends with ".txt"
}
}

关于c - 如何使用c程序检查子目录是否包含文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36589634/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com