数据附加到文件末尾而不是指定的偏移量

Data is appended to end of file instead of the specified offsets

我正在处理 4 个文件,并希望在指定的偏移量处向每个 them.I 中的每个文件注入一个字符串,我正在使用 fseek(),但数据被写入文件的末尾而不是预期 offsets.Why,我该如何解决:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define SZ 14
#define TARGET_NUM 4

long GetFileSize(FILE *fp);

int main(void)
{
    long offset[TARGET_NUM] = { 10,15,20,25 };

    const char *file_names[TARGET_NUM] = {
                                             "file1.txt", "file2.txt",
                                             "file3.txt", "file4.txt",
                                         };


    char dat[TARGET_NUM][SZ + 1] = {
                                       { '1','0','0','0','0','0','0','0', '0','0','0','0','0','0', 0 },
                                       { '0','1','0','0','0','0','0','0', '0','0','0','0','0','0', 0 },
                                       { '0','0','1','0','0','0','0','0', '0','0','0','0','0','0', 0 },
                                       { '0','0','0','1','0','0','0','0', '0','0','0','0','0','0', 0 },
                                   };

    FILE *fp[TARGET_NUM];

    long f_size;
    for (size_t n = 0; n < TARGET_NUM; n++) {
        fp[n] = fopen(file_names[n], "a");
        if (!fp[n]) {
            fprintf(stderr, "Error, file %s failed to open.\n", file_names[n]);
            goto cleanup;
        }
        f_size = GetFileSize(fp[n]);
        if (offset[n] < f_size) {
            fseek(fp[n], offset[n], SEEK_SET);
            fprintf(fp[n], "%s", dat[n]);
        }
    }

cleanup:
    for (size_t n = 0; n < TARGET_NUM; n++) {
        if (fp[n]) {
            fclose(fp[n]);
        }
    }
    return 0;
}

long GetFileSize(FILE *fp)
{
    fseek(fp, 0L, SEEK_END);
    long sz = ftell(fp);
    fseek(fp, 0L, SEEK_SET);
    return sz;
}

"a"模式表示数据将写入文件末尾。

尝试使用 "r+" 模式(读取 + 写入)。

引自N1570 7.21.5.3 fopen函数:

6 Opening a file with append mode ('a' as the first character in the mode argument) causes all subsequent writes to the file to be forced to the then current end-of-file, regardless of intervening calls to the fseek function.

这意味着用 "a" 模式打开的文件指针将忽略用 fseek 执行的操作。