简体   繁体   中英

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.

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

I came up with the following solution, In my program, I had to call a function multiple times which generated csv files. I defined the filename inside the loop as needed. This solution was based on the comments I received on this post.

/*generate csv files*/
int i;
char* filename; /*define the filename string array we will write to*/
int filename_len; /*we will need this when allocating memory*/

for (i=0;i<num_files;i++) {
    
    /*generate filename.
    this will be specific to your own code, depending on what you
    want to name the files. My filenames are i.pgm (i + 4 characters), 
    Remember you also need to malloc another for the null terminator
    at the end of char array*/

    filename_len = snprintf(NULL,0,"%d",i) + 5; /*calculate filename len*/
    filename = malloc(filename_len * sizeof filename[0]); /*malloc memory*/
    sprintf(filename, "%d.pgm",i); /*sprintf(destination, format string, variables)*/
    myfunction(filename, parameters); /*use filename as needed*/
    free(filename); /*free memory*/
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM