简体   繁体   中英

fscanf doesn't read all values in a text file when written and read in same .c file

There is this question that I need to write 10001 int values in a text file and then in the same program, these values should be read and stored in an int value to find out the total sum. But when I do both of these in the same program(same.c file?), then it doesn't read the last 200 values so the total is way less than it supposed to be. If you have any idea what causes this, please write because any help will be appreciated:) Thank you in advance!

Ps: I'm a beginner in coding and especially in C programming, forgive me if my code has terrible mistakes...

#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;   
 }

This works

#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;
        
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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