calling a variable in a string

19 Jul 2010

Hi,

I have a program which opens a file and records some data. I would like it to be able to open several files, and thus call each file a different name so as not to over-write them. I thought of setting up a count which incremented after each file was closed, and in the command to open the next file there would be a variable which would provide the number of the file opened. However, I cannot figure out how to call this variable inside the string which names the file.

FILE *fp = fopen("/local/analog.txt","w");
is what I have so far, and I was thinking of something on the lines of:

FILE *fp = fopen("/local/analog_x.txt","w");
where "x" is the name of the count at the time the file was opened.

 

Thanks for your time,

 

19 Jul 2010

Hi James,

You basically want to create a filename based on a variable, so you can use something like sprintf to create a string, then use that as your filename. So something like:

char filename[64];    
sprintf(filename, "/local/analog_%d.txt", x);
FILE *fp = fopen(filename, "w");
Hope that helps you!

Simon