0

我正在尝试将文件中的现有字符与新字符一一交换。新字符是通过从 ASCII 码中减去 1 来操作现有字符来获得的。该文件已经与文本一起存在,但由于某种原因我最终得到了一个无限循环。我究竟做错了什么?

#include <stdio.h>

int main()
{
  FILE *fp = fopen("myfile.txt", "r+");

  if (fp == NULL)
    printf("File cannot be opened.");
  else
  {
    // Used for retrieving a character from file
    int c;

   // Pointer will automatically be incremented by one after executing fgetc function
    while ((c = fgetc(fp)) != EOF)
    {
        // Decrement pointer by one to overwrite existing character
        fseek(fp, ftell(fp)-1, SEEK_SET);

        // Pointer should automatically increment by one after executing fputc function
        fputc(c-1, fp);

        printf("%c\n", c);
    }

    fclose(fp);
 }

    return 0;
}

-编辑- 我将 c 的数据类型从 char 更改为 int,但问题仍然存在。但是,通过在 fputc() 调用之后添加 fseek(fp, 0, SEEK_CUR) 解决了我的问题。我相信乔纳森莱弗勒的评论应该成为一个答案,因为这种问题没有从另一个问题中得到回答。

4

1 回答 1

0

尝试这个

#include <stdio.h>

int main(void){
    FILE *fp = fopen("myfile.txt", "r+");

    if (fp == NULL) {
        printf("File cannot be opened.");
        return -1;
    }

    int c;
    long pos = ftell(fp);
    while ((c = fgetc(fp)) != EOF){
        fseek(fp, pos, SEEK_SET);//In the case of text file Do not operate the offset.
        fputc(c-1, fp);
        fflush(fp);//To save the output.
        pos = ftell(fp);

        printf("%c\n", c);
    }
    fclose(fp);

    return 0;
}
于 2016-10-02T04:18:29.873 回答