1

I am making a c program that can save matrices and vectors in CSV files so I can then perform operations between them. In one of my functions I create a matrix with random numbers and then save it inside a CSV file.

The problem is that I don't know how to create a different file every time the function is run so each array can be stored in a different CSV file. Because of this I have to save all the matrices inside the same file which makes the rest of the process a lot harder. How could I make the function that makes a different file every time without it having completely random names.

Here is a link to the project in replit

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
iasonas zak
  • 35
  • 1
  • 6
  • 1
    check what files exist and then decide on names. dates and times can make for some uniqueness too. https://stackoverflow.com/questions/12489/how-do-you-get-a-directory-listing-in-c – Abel Dec 25 '21 at 00:45
  • 2
    I would just use a common prefix, followed by a 4 digit number, followed by the extension, e.g. `matrix5325.csv`. When the program starts, it should scan the directory to see which files already exist, and then use the first available number for the new file. Or you could find the largest number already used, and add 1. – user3386109 Dec 25 '21 at 00:58
  • You can write in a file 'lastnum.txt' , the last number you have used for your csv file name. When you use it , update the content of 'lastnum.txt' incrementing it by 1 . To combine string and number to craete the file name you can use `snprintf` look here: https://stackoverflow.com/questions/5172107/how-to-concatenate-string-and-int-in-c – Mario Abbruscato Dec 25 '21 at 01:26

1 Answers1

1

How could i make the function that makes a different file every time without it having completely random names.

Some possible solutions:

  • use timestamp as part of filename
  • use counter

For a timestamp, example code:

  char filename[80];
  snprintf(filename, sizeof(filename), "prefix.%d", time(NULL));
  FILE *fout = fopen(filename, "wt");

For a counter, use the same code as above, but check if the file prefix.${counter} exists (see man access). If it does, increment the counter and try again. If it doesn't, use the filename.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362