fopen(argv[1], "ab") 后 fseek 函数不工作

fseek function is not working after fopen(argv[1], "ab")

当我使用 "wb" 选项打开文件时,fseek 运行良好。 但是 fseek 函数在 fopen(argv[1], "ab").

之后无法正常工作

我的代码有问题吗?

这是代码。

student.h
struct student {
  int id;
};

main.c
#define START_ID 1201001
struct student rec;
FILE *fp = fopen(argv[1], "rb");
if(fp==NULL) {
    fp=fopen(argv[1], "wb");
} else {
    fclose(fp);
    fp=fopen(argv[1], "ab");
}
fseek(fp, (rec.id-START_ID)*sizeof(sec), SEEK_SET);

问题是 fseek 在使用 "a" 属性。见 here:

append: Open file for output at the end of a file. Output operations always write data at the end of the file, expanding it. Repositioning operations (fseek, fsetpos, rewind) are ignored. The file is created if it does not exist.

要解决这个问题,请尝试使用 "a+" 属性:

append/update: Open a file for update (both for input and output) with all output operations writing data at the end of the file. Repositioning operations (fseek, fsetpos, rewind) affects the next input operations, but output operations move the position back to the end of file. The file is created if it does not exist.

模式参数指向一个字符串。 如果字符串是以下之一(如下所述),则文件应以指定模式打开。否则,行为未定义。

r or rb Open file for reading.

w or wb Truncate to zero length or create file for writing.

a or ab Append; open or create file for writing at end-of-file.

r+ or rb+ or r+b Open file for update (reading and writing).

w+ or wb+ or w+b Truncate to zero length or create file for update.

a+ or ab+ or a+b Append; open or create file for update, writing at end-of-file.

因此,当您使用标志 ab 时,您是在说您希望在 文件结尾 处创建/打开文件进行写入。因此,出于同样的原因,您将无法使用 fseek

Solution:

尝试使用其他标志(如上所述)以便您可以使用 fseek

For more information refer:

http://man7.org/linux/man-pages/man3/fseek.3.html