I have a config file which includes how many files I need to create. So my program reads the config file and will create those files. Where I am stuck is I do not know before hand how many File pointers I need. I get to know quantity of files once the program reads the config file.

Any suggestions how to setup required #file pointers for those files so data can be written to them?

1-read the no. of files (N) from the config file to an integer variable.

2- You only need one file pointer to create N number of files in a loop. Name them e.g. file1, file2.. fileN

Something like this

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

int main()
{
    FILE **fp;
    char filename[20];
    int i;
        
    fp = malloc( sizeof(FILE *) * 10);
    
    if( fp != NULL )
    {
        for(i=0; i<10; i++)
        {
             sprintf(filename, "%s%d.txt", "file",i+1);
             
            if( ( fp[i] = fopen(filename, "a+") ) == NULL )
            {
                printf("Error: File \"%s\" cannot be opened\n", filename);
                continue;
            }
            fprintf( fp[i], "%s", "Hello There");
            fclose(fp[i]);
        }
    }
    else
    {
        printf("Error: No enough memory\n");
        getchar();
        return 1;
    }
    
    free(fp);
    
    printf("All done\n");
    getchar();
    return 0;
}

This could be done using just one single file pointer. But this is to demonstrate, how allocate FILE pointer dynamically.

ssharish

Correct. But to make it dynamic in its real sense, you need to pass the no. of files by command line arguments to main and then use that no. wherever you've used the fixed value 10..

True, I think he should be getting that value from the config file rather than comand line, I think thats what OP is looking for.

ssharish

Right. But just in order to demonstrate the dynamic nature, we must use command line arguments rather than using a constant value. Then the OP can set n to the value obtained from the config file in his code.

No issues :).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.