使用 while 循环打开文件 - C

Opening files with while loop - C

各位程序员大家好。 我没有什么问题。我不知道如何打开具有不同编号(在文件名中)的文件,从 1 到存在的任意数量的文件。

例如,我有两个(或最终 n)文件名为 game_1.txtgame_2.txt。这个循环应该打开这两个文件(或者最终都在那个文件夹中以这种模式打开)。

我遇到错误,即:

passing argument 2 of 'fopen' makes pointer from integer without a cast.

这是我的资料:

main()
{
    FILE *fr;
    int i=1;
    char b;

    while(fr=fopen("game_%d.txt",i) != NULL)
    {
        while(fscanf(fr,"%c",&b) > 0)
        {
            printf("%c",b);
        }
        i++;
    }


    return 0;
}

您可能需要这样的东西:

#include <stdio.h>

int main()
{
    FILE *fr;
    int i = 1;
    char b;

    while (1) // infinite loop, until broken out of
    {
        char to_open[32];
        snprintf(to_open, 32, "game_%d.txt", i);

        if ((fr = fopen(to_open, "r")) == NULL)
        {
            break;
        }

        while (fscanf(fr, "%c", &b) > 0)
        {
            printf("%c",b);
        }

        fclose(fr); // close the file after work is done

        i++;
    }

    return 0;
}

在原始代码中,对 fopen 的 API 调用会失败,因为它需要的第二个参数是一个字符串,包含打开文件时应使用的模式(在此我选择 "r" - Open file for input operations).

需要将 snprintf 调用到中间临时数组中,因为 fopen 不支持字符串格式化(例如使用 %d)。

之后,当下一个文件无法再使用break语句打开时,主循环就可以结束了。

在完成必要的工作后包含对 fclose 的调用也是一个好主意(在这种情况下,"work" 将是内部 while 循环),这样就没有不必要的内存和资源泄漏。

使用sprintf()构建文件名:

#include <stdio.h>
                // the c standard requires, that main() returns int
int main(void)  // you should put void in the parameter list if a
{               // when a function takes no parameters.
    char filename_format[] = "game_%d.txt";
    char filename[sizeof(filename_format) + 3];  // for up to 4 digit numbers

    for (int i = 1; i < 1000; ++i) {
        snprintf(filename, sizeof(filename), filename_format, i);
        FILE *fr = fopen(filename, "r");  // open for reading

        if(!fr)      // if the file couldn't be opened
             break;  // break the loop

        int ch;
        while ((ch = fgetc(fr)) != EOF)
            putchar(ch);

        fclose(fr);  // close the file when no longer needed.
    }                // since fr will be overwritten in the next
                     // iteration, this is our last chance.
    return 0;
}