c - 从目录中读取多个文件?

标签 c

我很难从与 exe 位于不同文件夹中的目录中打开文件。我设法阅读了一个文件。但是如何使用程序循环读取目录中存在的多个文件。

用于单个文件处理的代码如下:

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

int main()
{
    FILE *fp, *tp, *tl;
    char str_buff[1024] = { FALSE };
    char str[125];
    char strlengths[MAX_NO_OF_STRINGS]= { FALSE };
    //int Result;
    //int string_startflag = FALSE;
    int string_cntr = FALSE,i = 0, n = 0;

    fp = fopen("D:/folder/language/stringEnglish.h", "r");
    tp = fopen("New Text Document.txt", "w"); // open the file to Write
    tl = fopen("New Length Document.txt", "w"); // open the file to Write lengths

    while (NULL != fgets(str_buff, sizeof(str_buff), fp))
    {
        sscanf(str_buff, "%*[^\"]%*c%[^\"]%*c%*[^\n]%*c", str);

        //printf("%s\n", str);

        if (string_cntr > 6)
        {
            if (string_cntr<= MAX_NO_OF_STRINGS)
            {
                fprintf(tp, "%s\n", str);
                strlengths[i] = strlen(str);
                i++;
            }
        }
        string_cntr++;
    }

    for(n=0;n<(MAX_NO_OF_STRINGS-6);n++)
    {
        fprintf(tl,"%d\n",strlengths[n]);
    }

    fclose(fp);
    fclose(tp);
    fclose(tl);

    return 0;
}

因此我能够处理文件以解析文件中的变量并获取字符串的长度。问题是如何打开多个文件我在文件夹语言中有文件名:

stringItalian.h,stringLatvian.h,stringSlovakian.h,stringSlovenian.h,stringSpanish.h,stringSwedish.h,stringTurkish.h,stringUkrainian.h

如何循环打开这些名称的文件?

还有什么方法可以通用地给出文件夹 D:/folder/language 的路径?

最佳答案

您可以将路径作为命令行参数传递到您的程序中,如果它是第一个参数,则从 argv[1] 读取它的值,然后循环遍历您要读取的不同文件:

int main(int argc, char* argv[])
{
    ...
    const char* files[] = {"stringItalian.h", "stringLatvian.h",
                           "stringSlovakian.h", "stringSlovenian.h",
                           "stringSpanish.h", "stringSwedish.h",
                           "stringTurkish.h", "stringUkrainian.h"};
    int i;
    char fullpath[256];

    for (i=0; i<sizeof(files)/sizeof(files[0]); i++) {
        strcpy(fullpath, argv[1]);
        strcat(fullpath, files[i]);
        fp = fopen(fullpath, "r");

关于c - 从目录中读取多个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14770548/

相关文章:

c - lex 文件中无法识别的规则

c - 每次阅读我都必须重新打开/dev/urandom 吗?

Cygwin 在编译时找不到 dos.h 和 conio.h

c - 同一变量的两个枚举定义

c++ - 在 Visual C++ 中全局覆盖 malloc

c - 用C语言编写的快速排序

c - C中for循环的逻辑

c - 如何计算给定微 Controller 单元的机器周期时间

c - 如何读取数组中的字节

c - 如何为 print() 编写 Python 包装器?