【问题标题】:fscanf doesn't read all values in a text file when written and read in same .c file在同一个 .c 文件中写入和读取时,fscanf 不会读取文本文件中的所有值
【发布时间】:2021-04-09 11:34:52
【问题描述】:

有一个问题,我需要在一个文本文件中写入 10001 个 int 值,然后在同一个程序中,这些值应该被读取并存储在一个 int 值中以找出总和。但是,当我在同一个程序(同一个 .c 文件?)中执行这两项操作时,它不会读取最后 200 个值,因此总数比预期的要少。如果您知道是什么原因造成的,请写信,因为我们将不胜感激 :) 提前谢谢您!

Ps:我是编码的初学者,尤其是 C 编程的初学者,如果我的代码有严重的错误,请原谅我......

#include <stdio.h>

 int main ()
 {
 //a)

 FILE * fp = fopen ("deneme.txt","w");

 int I;

 for(i=0;i<=10001;i++) {
            
        if(i%10==0){
            
            fprintf(fp,"\n");
            
        }
        
            fprintf(fp,"%5d  ",i);
        
}
´ /* when i write and read in different .c 
 files, it shows the correct answer which is:
 
 Total sum: 50015001
 from how many values: 10002

 but instead it gives me this:
 Total sum: 48083730
 from how many values: 9808
 
 */´
//b)

       FILE* file = fopen ("deneme.txt", "r");
       int j,counter =0;
       int sum = 0;  
  
      while ((fscanf (file, "%d", &j)) != EOF)
      {  
         counter++;
          sum+=j;
           
      }
      
      fprintf(stdout,"Total sum: %d\n",sum);
       printf("from how many values: %d",counter);
    
    
      fclose (file);
  
   return 0;   
 }

【问题讨论】:

  • 您是否在写入后但在打开阅读之前关闭文件?关闭文件的操作将刷新缓冲区,以便这些缓冲区中的数据可供读取。
  • 天啊,你拯救了我的一天!!!非常感谢!

标签: c printf scanf stdout stdin


【解决方案1】:

这行得通

#include <stdio.h>

int main ()
{
    //a)

    FILE * fp = fopen ("deneme.txt","w");
    int i;//YOU HAD A TYPO HERE
    for(i=0;i<=10001;i++) { 
        if(i%10==0){
            fprintf(fp,"\n");
        }
        fprintf(fp,"%5d  ",i);
    }

    fclose(fp); //ADD THIS

    //b)

    FILE* file = fopen ("deneme.txt", "r");
    int j,counter =0;
    int sum = 0;  
    while ((fscanf (file, "%d", &j)) != EOF)
    {  
        counter++;
        sum+=j;
        
    }
    fprintf(stdout,"Total sum: %d\n",sum);
    printf("from how many values: %d",counter);
    fclose (file);
    return 0;
        
}

【讨论】:

  • 非常感谢! fclose 就像一个魅力。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-29
  • 1970-01-01
  • 2017-06-22
  • 2018-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多