是否将文件指针移动到文件的开头

是否将文件指针移动到文件的开头

本文介绍了如果文件是在“a+b"中打开的,fseek() 是否将文件指针移动到文件的开头?模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用a+b"模式打开一个文件,即如果它不存在,它会自动创建,但如果它存在,我不想覆盖它.我希望能够读取和写入文件.

I wish to open a file using the "a+b" mode, i.e. if it does not exist it is created automatically, but if it does I don't want to overwrite it. I want to be able to read and write to the file.

该文件是二进制文件,我想在其中保存特定 struct 的记录.所以我想对我想要的记录执行 fseek(),然后使用 fwrite() 保存记录.

The file is binary, and I want to save records of a specific struct in it. So I want to do fseek() to the record I want and then save the record using fwrite().

代码如下(MyRecordtypedefstruct,而 FILENAMEtypedefcode>#define 到文件名):

The code looks as follows (MyRecord is a typedef to a struct, while FILENAME is a #define to the file's name):

int saveRecord(MyRecord *pRecord, int pos)
{
    FILE* file = fopen(FILENAME, "a+b");
    if (file == NULL)
    {
        printf("Unable to open file %s\n", FILENAME);
        return 0;
    }

    fseek(file, pos * sizeof(MyRecord), SEEK_SET);
    fwrite(pRecord, sizeof(MyRecord), 1, file);
    fclose(file);
    return 1;
}

但是,即使我将 pos 设置为 0,此代码也只是将记录附加到文件的末尾.为什么 fseek()SEEK_SET 在追加模式下工作?

However this code just appends the record to the end of the file, even if I set pos to 0. Why isn't fseek() with SEEK_SET working in append mode?

我知道我可以简单地用r+b"打开它,如果它失败了用wb"打开它,但我想知道为什么这不起作用以及为什么fseek()SEEK_SET 将文件指针留在最后.任何对记录此行为的地方的引用都表示赞赏(因为我找不到任何地方,或者我使用了错误的关键字).

I know I can simply open it with "r+b" and if it fails open it with "wb", but I want to know why this doesn't work and why fseek() with SEEK_SET is leaving the file pointer at the end. Any references to places where this behaviour is documented appreciated (because I couldn't find any, or I am using the wrong keywords).

推荐答案

那是因为在 a 模式下,写入 FILE* 总是附加到末尾.fseek 在这种模式下只设置读指针.C 标准 7.19.5.3 fopen 中记录了这一点:

That's because in a mode, writing to the FILE* always appends to the end. fseek only sets the read pointer in this mode. This is documented in the C standard, 7.19.5.3 fopen:

以追加模式打开文件('a' 作为模式参数中的第一个字符)导致对文件的所有后续写入都被强制写入当前的文件结尾,不考虑对 fseek 函数的干预调用.

这篇关于如果文件是在“a+b"中打开的,fseek() 是否将文件指针移动到文件的开头?模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:01