'Increment file name in C [closed]
I wish to increment the file name as below, and output them as files themselves. So there will be a total of 1000 files in my file directory.
File1.txt, File2.txt, …, File100.txt, File101.txt, …, File1000.txt.
How can I code it in C program?
char filename[1000][50];
FILE *fileunit[1000];
char temp[] = “file0.txt”;
char *fp;
for (i = 0; i < 1000; i++) {
fp = temp;
fp += 4;
*fp += 1;
fp -= 4;
*temp = *fp;
strcpy(filename[i], temp);
fileunit[i] = fopen(filename[i], “w”);
}
With this, I am able to output File1.txt, …, File9.txt. How can I improve my codes to output files until File1000.txt. Thank you!
Solution 1:[1]
Probably you don't know the snprintf function, which does exactly what you want. I'll leave here an example, and you can find here the Posix documentation.
You can be tempted by using sprintf and in this case it will work fine because you know exactly how large is your buffer. However, for more dynamic cases where the user does not know a priori which is the length of the final string, snprintf is the safe option, which gives you the chance to know if the string was truncated.
#define STR_MAX_LEN 256
// Init to all zeros, so that you have 0 ended strings.
char filename[STR_MAX_LEN] = {0};
int ret;
for ( int i = 1; i <= N_FILES; i++)
{
// -1 because we want to leave a "0" at the end.
ret = snprintf(filename, STR_MAX_LEN-1, "my_file_%d.txt", i);
if( ret < 0) // Error handling
else if( ret >= STR_MAX_LEN-1 ) // Truncated
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
