gpt4 book ai didi

c - fgetc 函数无法正常工作

转载 作者:行者123 更新时间:2023-11-30 14:42:31 27 4
gpt4 key购买 nike

我正在测试 fgetc() 函数,但它无法正常工作(我以前使用过这个函数,所以我知道它是如何工作的)

#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *file = NULL;
int n;

file = fopen("test.txt", "w+");
if(file != NULL)
{
fputs("ab", file);
printf("%c", fgetc(file));
}
else
{
printf("error");
}
return 0;
}

输出应该是“a”,但它是其他东西

最佳答案

文件已打开以进行写入和读取,但您需要 fseek 到文件中的正确位置(此处为开头)。特别是,在写入和读取之间切换时,您需要 fseekfflush

When the "r+", "w+", or "a+" access type is specified, both reading and writing are enabled (the file is said to be open for "update"). However, when you switch from reading to writing, the input operation must encounter an EOF marker. If there is no EOF, you must use an intervening call to a file positioning function. The file positioning functions are fsetpos, fseek, and rewind. When you switch from writing to reading, you must use an intervening call to either fflush or to a file positioning function.

无论如何,写入文件后,文件指针位于错误的位置,无法读取刚刚写入的内容。

所以代码就变成了

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
FILE *file = NULL;
file = fopen("test.txt", "w+");
if(file != NULL) {
fputs("ab", file);
fseek(file, 0, SEEK_SET);
printf("%c", fgetc(file));
fclose(file);
}
else {
printf("error");
}
return 0;
}

如果您想继续写入文件,则必须 fseek 到文件末尾。

关于c - fgetc 函数无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54393729/

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