Search code examples
cvariablesdependent-name

Create new files, whose name depends on a variable from the program


I'm trying to write a program that will save "X" number of simple textfiles- however, X is determined by the user once the program has run. I can't seem to find any help on the net as to how to solve the following two things, so any tips will be massively appreciated!

1) How do I declare these textfiles at the start of the program if I don't know how many there will be?

  • So far, I'm used to using:

    FILE* outfile;
    
  • But what I really need is:

    FILE* outfile_0, outfile_1, outfile_2... outfile_X;
    
  • The solution that comes to mind looks like a loop, but I know that this won't work!

    for (i=0;I<X;i++){
        FILE* outfile_i     // obviously, this just literally calls it "outfile_i" 
    }
    

2) How do I name them?

  • I want to call them simple names, such as "textfile_1, textfile_2" etc, but I don't see how that would be possible using:

    outfile=fopen("C:\\textfile.txt","w");
    
  • Again, I thought perhaps making a loop (?!) but I know that this won't work:

    for(i=0;i<X;i++){
        outfile_i=fopen("C:\\textfile_i.txt","w");
    }
    

There's absolutely no way of knowing what variable "X" is before running the program.

EDIT: Problem solved- I wasn't aware you could create arrays of "FILE*", thanks for all the help!


Solution

  • You have to put all your FILE * variables in an array. I would do:

    char filename[80];
    char number[10];
    
    /* Allocate our array */
    FILE ** files = malloc((sizeof(FILE *) * X) + 1); /* We allocate a size of X+1 because we'll have X elements + a last NULL element. */
    
    /* Populate our array */
    for (int i = 0; i < X; i++)
    {
        strcpy(filename,"C:\\textfile_");
        itoa(i, number, 10); /* Here 10 means we use decimal base to convert the integral value. */
        strcat(filename, number);
        strcat(filename, ".txt");
    
        files[i] = fopen(filename, "w");
    }
    files[i] = NULL; /* Here we set the last element of our array to NULL (so when we iterate over it we can stop when we encounter NULL). */
    

    Then you can access all your files like this:

    for (int i = 0; files[i] != NULL; i++)
    {
        FILE * current = files[i];
        /* Do something with "current" here. */
    }
    

    PS: Some security checks are required:
    malloc → Verify it doesn't return NULL.
    itoa → Verify that output string is valid.
    fopen → Verify that the file was opened.