c - C语言中如何清除缓冲区?

标签 c file printf buffer fwrite

我有以下问题:

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 在代码中),程序将找到该位置(在二进制文件中)。 然后,用户通过 (scanf("%s", todo.title);) 输入 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) 或类似的函数来向后移动并覆盖刚刚读取和更改的记录。

关于c - C语言中如何清除缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59395535/

相关文章:

C - 将输出写入文件

java - 将数组作为参数传递 : C and Java

C# 文件浏览至 textbox.text only .doc .txt 等

c - 读取 csv 文件并存储在缓冲区中时出现问题

c - 延迟之前的 printf 在 C 中不起作用

c - 尝试用 C 语言编写输出棋盘格的代码

c - lex 前缀 undefined symbol yyparse

无法使用c中的循环链表中的条件删除节点

c - AF_XDP : `BPF_MAP_TYPE_XSKMAP` only has entries with `Operation not supported`

Java - 如何根据请求打印文件中的数据?