gpt4 book ai didi

C 读取并替换字符

转载 作者:行者123 更新时间:2023-12-02 06:19:03 25 4
gpt4 key购买 nike

我正在尝试读取一个文件并将每个字符替换为 ASCII 表中相应的字符。它可以正确打开文件,但会继续读取第一个字符。

int main(int argc, char * argv[])
{
FILE *input;
input = fopen(argv[2], "r+");
if (!input)
{
fprintf(stderr, "Unable to open file %s", argv[2]);
return -1;
}

char ch;
fpos_t * pos;
while( (ch = fgetc(input)) != EOF)
{
printf("%c\n",ch);
fgetpos (input, pos);
fsetpos(input, pos-1);
fputc(ch+1, input);
}
fclose(input);
return 1;
}

文本文件是

abc
def
ghi

我很确定这是由于 fgetpos 和 fsetpos 但如果我删除它然后它会在文件末尾添加字符,下一个 fgetc 将返回 EOF 并退出。

最佳答案

处理以更新模式打开的文件时必须小心。

C11 (n1570), § 7.21.5.3 The fopen function

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.

所以你的阅读可能看起来像这样:

int c;

while ((c = getc(input)) != EOF)
{
fsetpos(/* ... */);
putc(c + 1, input);
fflush(input);
}

顺便说一下,你会遇到 'z' 字符的问题。

关于C 读取并替换字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16254497/

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