C 读取并替换字符

标签 c

我正在尝试读取一个文件并将每个字符替换为 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/

相关文章:

c - 使用 c 的数组中的哨兵值

c - C标准中对可变修改类型的switch语句约束的解释

C:在函数中访问结构的成员

python - 自动化 vi/nano 编辑器进行 git commit --amend

c - threadpools - 老板/ worker 与同行(工作人员)模型

c - AtmelStudio编译代码: How to optimize compiler

c - 调用函数时出现不兼容指针类型错误

c - 指针声明的区别?

c - 如何获取数组的移动平均值

c - 从文件中读取行不返回全部