Saving files on C
I want to save files on computer.I can use fwrite commands.
But I have to enumarate files,like file01,file02, .. inside in the for cycle while saving using fwrite commands.
开发者_如何学GoSo I have to save ;for example ten files (file01,fle02,file03....,file10...)
Could you advise me a simple example code?
Inside a loop you need to
- build the filaname
- open the file
- write data
- close the file
C99 example (snprintf()
is "new"), with lots of details omitted
for (j = 0; j < 10; j++) {
snprintf(buf, sizeof buf, "file%02d.txt", j + 1); /* 1. */
handle = fopen(buf, "w"); /* 2. */
if (!handle) /* error */ exit(EXIT_FAILURE); /* 2. */
w = fwrite(data, 1, bytes, handle); /* 3. */
if (w != bytes) /* check reason */; /* 3. */
fclose(handle); /* 4. */
}
You need to open the files one by one with fopen, something like this:
char filename[128]; // (128-1) characters is the max filename length
FILE *file;
int i;
for (i = 0; i < 10; ++i) {
snprintf(filename, 128, "file%02d", i);
file = fopen(filename);
// do stuff with file
fclose(file);
}
精彩评论