Medo
Medo

Reputation: 1032

Writing a file into separate new files

Suppose I read a file into a buffer:

FILE *fp = fopen("data.dat", "rb");    
double *buf = calloc(100, sizeof(double));
fread(buf, sizeof(double),100, fp);

My goal is to re-write the loaded file into two separate files each of which has 50 elements (First 50 goes to file and the last 50 goes to another one). I do the following:

    int c;
    FILE *fp_w= NULL;
    for (c = 0; c < 2; ++c) {
        sprintf(filename, "file_%d%s", c, ".dat");
        fp_w = fopen(filename, "wb");
        fseek(fp_w, 50*sizeof(double), SEEK_CUR);
        fwrite(buf, sizeof(double), 50, fp_w);

    }
    fclose(fp_w);

However, I don't actually get the correct division. In other words, I feel the pointer fp_w does not move to the position 50 very well and I don't know how to handle fseek in another way. Any help is appreciated.

Upvotes: 2

Views: 53

Answers (1)

Jabberwocky
Jabberwocky

Reputation: 50782

There are many issues:

  1. You don't close the file once you have written to it
  2. You seek into the file to write whithout any need
  3. You write twice the same buffer to both files.

You probably need this:

int c;
FILE *fp_w= NULL;
for (c = 0; c < 2; ++c) {
    sprintf(filename, "file_%d%s", c, ".dat");
    fp_w = fopen(filename, "wb");              

    // buf + 50*c to get the right part of the buffer
    // (buf for the first part and buf+50 for the second part)
    fwrite(buf + 50*c, sizeof(double), 50, fp_w);

    // close file right here, not outside the loop
    fclose(fp_w);
}

Upvotes: 6

Related Questions