Search code examples
arrayscstringc-strings

How to generate a string array of numerical filenames in C


I have a C program that generates a number of matrices I want to store in CSV files, which I later make images and then a GIF out of. The program is working currently, but the way I have defined the filenames is awkward. Currently I hardcode it in like so:

char filenames[5][10] = {
                         "0.csv",
                         "1.csv",
                         "2.csv",
                         "3.csv",
                         "4.csv",
                         "5.csv"
                        };

Would there be a way to programmatically generate an array like this, say in a for loop? I have an intuition it would look something like this:

int num_files=10;
char** filenames;
int i;

for(i=0;i<num_files;i++) {
    filenames[i] = malloc(something) /*some sort of memory allocation*/
    filenames[i] = format("%d.csv",i); /*some sort of string formatting process*/
}

Thanks for the help.


Solution

  • char (*genArray1(size_t nfiles))[10]
    /* can be also: void *genArray(size_t nfiles) */
    {
        char (*array)[10] = malloc(sizeof(*array)* nfiles);
        if(array)
        {
            for(size_t fileno = 1; fileno <= nfiles; fileno++)
                snprintf(array[fileno-1], sizeof(*array), "%zu.csv", fileno);
        }
        return array;
    }