简体   繁体   English

我在此程序中得到了意外的输出

[英]I am getting unexpected output in this Program

I just want to replace specific character from file. 我只想替换文件中的特定字符。 for example, I want to replace character 'l' with character 'p'. 例如,我想用字符“ p”替换字符“ l”。 is it correct way ? 这是正确的方法吗?

int main() {
  FILE * ptr;
  ptr = fopen("D:\f4.txt", "r+");

  if (ptr == NULL) {
    printf("file cant be opened");
    exit(0);
  }

  char ch = fgetc(ptr);
  while (ch != EOF) {
    if (ch == 'l') {
      fseek(ptr, -1, 1);
      fputc('p', ptr);
    }

    ch = fgetc(ptr);
  }

  fclose(ptr);
}

suppose content in my file is "hello everyone" so output should be like "heppo everyone" but it writes in file "hepepepepepepepepepepepepepepep" continuesly. 假设我文件中的内容是“大家好”,那么输出应类似于“ heppo每个人”,但它将继续写在文件“ hepepepepepepepepepepepepepepepepep”中。 please help me to find why this happen. 请帮助我找出原因。

Please note this from the man page for fopen() . 请从手册页中的fopen()注意这一点。

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"). 指定“ r +”“ w +”“ a +”访问类型时,将同时启用读取和写入功能(据说该文件已打开以进行“更新”)。 However, when you switch from reading to writing, the input operation must encounter an EOF marker. 但是,当您从读取切换为写入时,输入操作必须遇到EOF标记。 If there is no EOF, you must use an intervening call to a file positioning function. 如果没有EOF,则必须对文件定位功能进行中间调用。 The file positioning functions are fsetpos , fseek , and rewind . 文件定位功能是fsetposfseekrewind When you switch from writing to reading, you must use an intervening call to either fflush or to a file positioning function. 从写入切换为读取时,必须使用中间调用来fflush或使用文件定位功能。 (my italics) (我的斜体字)

So after you wrote 'p' to the file, it is not enough to carry on reading as though nothing has happened, you must fseek to the original position, obtained by ftell , or fflush the file. 因此,在将'p'写入文件后,就好像什么都没发生一样,仅进行读取是不够的,您必须fseekftell获得的原始位置,或者将文件fflush

Also don't use magic numbers: in fseek you should use SEEK_CUR not 1 . 也不要使用幻数:在fseek ,应使用SEEK_CUR而不是1

Finally, function fgetc returns an int type, not char . 最后,函数fgetc返回一个int类型,而不是char This allows EOF to be distinguished from the data byte 0xFF . 这允许将EOF与数据字节0xFF区分开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM