簡體   English   中英

如何使用C程序檢查子目錄是否包含文本文件

[英]How to check if a sub-directory contains text files using c program

我有一個目錄說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"
    }
}

無需打印目錄,您只需將其放在if語句中即可檢查它是否為所需文件。 如果是:返回目錄名稱,否則繼續。 您可以將所有內容置於for循環中,以便檢查每個目錄。

例如:

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

作為另一種特定於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文件的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM