如何清除C中的缓冲区?

How to clear buffer in C?

我有以下问题:

void edit(FILE *f, int cnt)
{
    int i = 0;
    int offset = 0;
    rewind(f);

    schedule todo;
    schedule *p = &todo;

    fprintf(stdout, "\n%s\n", "------------------------------------------------");
    fread(&todo, sizeof(schedule), 1, f);
    while (!feof(f)) {
        fprintf(stdout, "%6d%18s\n",                                
            ++i, todo.title);
        fread(&todo, sizeof(schedule), 1, f);
    }
    fprintf(stdout, "%s\n\n", "-------------------------------------------------");
    fprintf(stdout, "%s\n\n", "Number: ");

    scanf("%d", &i);
    getchar();

    rewind(f);
    offset = (long) sizeof(schedule);
    fseek(f, (i - 1)*offset, SEEK_CUR);

    fread(&todo, sizeof(schedule), 1, f);
    printf("Edit: %s\n", todo.title);
    fprintf(stdout, "%6d%18s%8s%10s%8d\n",                              
        todo.number, todo.title, todo.where, todo.details, todo.importance);

    scanf("%s", todo.title);

    fwrite(&todo, (long)sizeof(todo.title), 1, f);

}

这是编辑数据代码的一部分。 这是我所期望的。

如果用户输入数字(代码中的 i),程序将找到位置(在二进制文件中)。 然后,用户将 todo.title 放入 (scanf("%s", todo.title);) ,程序将使用 fwrite(&todo, (long)sizeof(todo.title), 1, f);

我收到了类似

的警告

Expression: ("Flush between consecutive read and write.", !stream.has_any_of(_IOREAD))

我认为缓冲区有问题,但我无法解决这个问题。

如果您打开文件进行更新(读取和写入),则 C11 标准要求:

§7.21.5.3 The fopen function

¶7 When a file is opened with update mode ('+' as the second or third character in the above list of mode argument values), both input and output may be performed on the associated stream. However, output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file. Opening (or creating) a text file with update mode may instead open (or create) a binary stream in some implementations.

引用自C11规范,但在所有版本的标准中基本没有变化

请注意,您必须执行寻道操作,即使它只是 fseek(f, 0, SEEK_CUR),在读取和写入操作之间,以及写入和读取操作之间。

您的代码有一个 fread(),后跟一个 fwrite(),中间没有 fseek()。这可能是一个疏忽,因为您更改了记录并用更新的信息覆盖了文件中的下一条记录。您可能需要一个 fseek(f, -(long)sizeof(schedule), SEEK_CUR) 左右的时间来返回并覆盖刚刚读取和更改的记录。