gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:08:07 25 4
gpt4 key购买 nike

我正在处理 4 个文件,并希望在每个文件的指定偏移处注入(inject)一个字符串。我正在使用 fseek() 但数据被写入文件末尾预期偏移量。为什么,以及如何修复它:

#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执行的操作。

关于c - 数据附加到文件末尾而不是指定的偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37632065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com