-1

我正在尝试将一些数据输入到文件中,然后在控制台上读取并打印它。

这是我的代码:

  fp=fopen("user1","w+");
  char line[1000];
  char *c;
  //write on file

  while(1)
  {
      fgets(line,sizeof(line),stdin);
      if(strcmp(line,":wq\n")==0)   //input ends when user enters :wq
          break;
      else
          fputs(line,fp);
  }
  //read from file
  fflush(stdin);

  while(1)
  {
      c=fgetc(fp);
      if(c==EOF)
          break;
      else
          printf("%ch",c);
   }

我输入数据为

比萨

:wq

输出:

 h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h  h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h 

问题是什么?

4

1 回答 1

1

我看到两个问题

1)您fgetc分配给一个字符点。那是错的。它应该是一个 int

2) 写入文件后,应先将其关闭,然后再打开读取

就像是:

  fp=fopen("user1","w+");
  char line[1000];
  int c;             // notice ......

  //write on file    
  while(1)
  {
      fgets(line,sizeof(line),stdin);
      if(strcmp(line,":wq\n")==0)   //input ends when user enters :wq
          break;
      fputs(line,fp);
  }
  fclose(fp);


  //read from file
  fp=fopen("user1","r");
  while(1)
  {
      c=fgetc(fp);
      if(c==EOF)
          break;
      printf("%ch",c);
  }
  fclose(fp);
于 2017-10-18T16:35:12.033 回答