-
Question on strings
Hi,
I'm a begginer in C (learning it for fun) and I have a question regarding strings.
I programmed a simple 'extractor' for a file format and I want each of my files to be named sequentially as FILE00.ext, FILE01.ext, etc.
Here is the code snippet that write the files:
Code:
for (i = 0; i < num_of_files; i++) {
fseek(input, (file_offset[i] + start_offset), SEEK_SET);
FILE *ripped_file = fopen( filename , "w+b");
for ( j = 0; j < ( file_offset[i+1] - file_offset[i] ); j++) {
ch = getc(input);
putc(ch, ripped_file);
}
fclose(ripped_file);
}
Everything works fine, but how can I make the "filename" be incremented each time? I thought of doing some like counter++ (with an integer) but I'm not sure how can I append that to the filename. Can someone give an actual example of this?
-
Code:
....
char filename[10]; //the name, like FILE in your example, or anything else you would like
char varStr[7]; // the number followed by .ext
char newFilename[17]; //the filename you want
...
strcpy(varStr, "00.ext"); //varStr is "00.ext"
newFilename = strcat(filename, varStr); //this appends the varStr to the filename
...
//This creates FILE00.ext, FILE01.ext etc etc
FILE * fd[5];
for (int i=0; i<5; ++i) {
newFilename = strcat(filename, varStr);
fd[i] = fopen(newFilename, "w");
varStr[1]++;
}
Notice that varStr[1] = '0' at the beggining. If you increase it it will be '1' (not 1, but the char '1'). And so on. At the tenth file of course you have to set varStr[1] = '0' and varStr[0] = '1'. Last note, every string is null-terminated. If you make that sure then it should work for a size less than the maximum size of the array
-
Thank you, that's very helpful :).
I thought the "++" increment could be only used for integers, so I had the wrong idea that I had to use some sort of typecast. It's much simpler, thank you again.
Edit: Ops, there a few problems with your solution. After 9, I start to get random ASCII chars instead of a number, so I guess this is not quite what I want.
-
Code:
int filenum = 0;
char filename[100];
// Repeat this
sprintf(filename, "my file%i.txt", filenum);
filenum++;