Search code examples
cfilefopen

Opening files with while loop - C


Hello fellow programmers. I have little problem. I cannot figure out how to open files with different numbers (in the filename) going from 1 to whatever number of files exist.

For example, I have two (or eventually n) files named game_1.txt and game_2.txt. This loop should open these two files (or eventually all with this pattern, in that folder).

I am getting errors, namely:

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

Here is what I have:

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;
}

Solution

  • Use sprintf() to build the filename:

    #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;
    }