Pakito Gama
Pakito Gama

Reputation: 106

How do I continuously generate a name for a file which is increasing ? For example: book1.txt, book2.txt etc

So I am trying to write a begginers program in which it is necessary to create a series of files, depending on the users choosing option, and where the first file created should be name by for example "book1.txt" and second one "book2.txt" etc...

FILE *fnew;
int num;  //i do have a lot of code before to get the 'num' value from where I want, don't bother it;

char filename[]= "bookX.txt";
filename[4]=num+1;

fnew = fopen(filename,"w");
fclose(fnew);

Upvotes: 0

Views: 31

Answers (1)

dbush
dbush

Reputation: 224577

You can use sprintf to build the filename:

sprintf(filename, "book%03d.txt", num);

This will create files named booknnn.txt, where nnn is the number in question padded with 0's, ex. book001.txt, book002.txt.

Upvotes: 3

Related Questions