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

3
  • 1
    check what files exist and then decide on names. dates and times can make for some uniqueness too. stackoverflow.com/questions/12489/… Commented Dec 25, 2021 at 0: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. Commented Dec 25, 2021 at 0: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: stackoverflow.com/questions/5172107/… Commented Dec 25, 2021 at 1:26

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.