将文件写入单独的新文件

Med*_*edo 2 c

假设我将文件读入缓冲区:

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

我的目标是将加载的文件重新写入两个单独的文件,每个文件有50个元素(前50个文件到达文件,最后50个文件到另一个文件).我做以下事情:

    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);
Run Code Online (Sandbox Code Playgroud)

但是,我实际上并没有得到正确的分工.换句话说,我觉得指针fp_w不能很好地移动到位置50,我不知道如何以fseek另一种方式处理.任何帮助表示赞赏.

Jab*_*cky 6

有很多问题:

  1. 写入后,不要关闭文件
  2. 你寻求进入文件,无需任何需要
  3. 您将两个相同的缓冲区写入两个文件.

你可能需要这个:

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);
}
Run Code Online (Sandbox Code Playgroud)