开发者

Saving files on C

开发者 https://www.devze.com 2023-03-03 10:29 出处:网络
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.

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.

开发者_如何学Go

So 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

  1. build the filaname
  2. open the file
  3. write data
  4. 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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消