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

时间:2016-04-13 05:49:44

标签: c

我有一个目录说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);
}

3 个答案:

答案 0 :(得分:1)

您可以使用标志。如果在".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"
    }
}

答案 1 :(得分:0)

您可以将其放在if语句中,以检查它是否是所需的文件,而不是打印目录。如果是:返回目录名,否则继续。你可以把它全部放在for循环中,这样你就可以检查每个目录。

例如:

If(!strcmp(filename, filetofind))
    Return dirname

答案 2 :(得分:0)

作为替代方案,懒惰和Windows特定的解决方案,您可以通过这种方式将作业发送到Windows for命令:

#include <stdio.h>
#include <string.h>

#define MAX_LENGTH 1024

int main()
{
    char buffer[MAX_LENGTH];

    FILE *f = _popen("cmd /c @for /R C:\\Users\\xp\\Desktop\\Star1\\ %i in (.) do @if exist \"%~i\"\\*.txt echo %~fi 2> NUL", "r");
    if (f != NULL)
    {
        while (fgets(buffer, MAX_LENGTH, f) != NULL)
        {
            int len = strlen(buffer);
            if (buffer[len - 1] == '\n')
            {
                buffer[--len] = '\0';
            }

            printf("Found: %s\n", buffer);
        }
        _pclose(f);
    }
}

编辑:修复答案以提供目录列表而不是.txt文件。

相关问题