tsaiwn@magpie % cat -n readin.c 1 //readin.c --- fopen/fgets --- copyLeft by tsaiwn@csie.nctu.edu.tw 2 #include 3 #include 4 char FNAME[ ] = "abc.txt"; 5 int main( ) { 6 FILE* fp; 7 static char buf[99]; 8 double ans, x; 9 int n; 10 fp = fopen(FNAME, "rt"); // open for read, text file 11 if(fp == 0) { 12 fprintf(stderr, "open file %s ", FNAME); 13 perror("Error "); 14 return 38; 15 } 16 ans = n = 0; 17 fgets(buf, sizeof(buf), fp); 18 while( !feof(fp) ) { 19 ++n; x = atof(buf); 20 ans += x; 21 printf("%f ", x); 22 fgets(buf, sizeof(buf), fp); 23 } 24 printf("\nTotal %d items. Sum = %f\n", n, ans); 25 return 0; 26 } tsaiwn@magpie % cat abc.txt 1.2 2.3 3.4 tsaiwn@magpie % gcc readin.c tsaiwn@magpie % ./a.out 1.200000 2.300000 3.400000 Total 3 items. Sum = 6.900000 tsaiwn@magpie % cat -n readin.cpp 1 //readin.cpp --- cin.getline --- copyLeft by tsaiwn@csie.nctu.edu.tw 2 //g++ readin.cpp -Wno-deprecated ; ./a.out 3 #include 4 #include 5 #include 6 char FNAME[ ] = "abc.txt"; 7 int main( ) { 8 fstream in; // required 9 static char buf[99]; 10 double ans, x; 11 int n; 12 in.open(FNAME, ios::in); // open for read, text file 13 if(in.fail( ) ) { 14 cerr << " Error open file " << FNAME << endl; 15 perror("Error "); 16 return 38; 17 } 18 ans = n = 0; 19 in.getline(buf, sizeof(buf) ); // read first record 20 while( !in.eof() ) { 21 ++n; x = atof(buf); // need 22 ans += x; 23 cout << x << " "; 24 in.getline(buf, sizeof(buf) ); 25 } 26 cout << "\nTotal "<< n << " items. Sum = "; 27 cout << ans << endl; 28 return 0; 29 } tsaiwn@magpie % g++ -Wno-deprecated readin.cpp tsaiwn@magpie % ./a.out 1.2 2.3 3.4 Total 3 items. Sum = 6.9 tsaiwn@magpie % exit exit