You are here:

C/Read file

Advertisement


Question
-------------------------
Dear Sir,

I have try the following but the code keep on continuos looping and it only display 0 to 5, 6 to 9 not appearĄ­.please help, thanksĄ­

#include <stdio.h>

int main()
{
   FILE *f;
   int s[10],i=0, sum=0;

   f=fopen("num.txt","r");
   if (!f)
       return 1;

while (!feof(f)){
       sum=sum + s[i];
       printf("%d",s);
       i++;
   }
  
   fclose(f);
   return 0;
}


num.txt content:
0
1
2
3
4
5
6
7
8
9




Followup To
Question -
Dear sir,

can you tell me how to Read a number field in a sequential file so that i can sum up this number in C language? Thanks..


Answer -
Read the file using fread() (If your file is binary) or fscanf() (If your file is ascii).
If you have many consecutive numbers, then read them in a loop.
Read them to a variable num.
Go on adding them to another variable sum like this:

sum = sum + num;

At the end sum will have the sum of all the numbers.

-ssnkumar

Answer
Here is the corrected code:

#include <stdio.h>

int main()
{
       FILE *f;
       int s[10], i = 0, sum = 0;

       f=fopen("num.txt","r");
       if (!f) return 1;

       while (fscanf(f, "%d", &(s[i])) > 0)
       {
         sum = sum + s[i];
         printf("%d\n", s[i]);
         i++;
       }

       printf("SUM = %d\n", sum);

       fclose(f);
       return 0;
}

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.