08:58am ccbsd3:readfile/> g++ testfile.cpp 08:58am ccbsd3:readfile/> ./a.out Test file I/O --- by tsaiwn@csie.nctu.edu.tw == call test1 to test printf with wrong %format == in test1 .. kk=12345678 ?? 12345678 ??? 12345678 Correct kk=12345678 ================ 1 2 3 4 5 6 7 8 9 2 4 6 8 10 12 14 16 18 3 6 9 12 15 18 21 24 27 4 8 12 16 20 24 28 32 36 5 10 15 20 25 30 35 40 45 6 12 18 24 30 36 42 48 54 7 14 21 28 35 42 49 56 63 8 16 24 32 40 48 56 64 72 9 18 27 36 45 54 63 72 81 TEST.del created! -rw------- 1 tsaiwn faculty 22 Jan 3 12:05 TEST.del Hey, you! Hello world ÿ % cat -n TEST.del 1 Hey, you! 2 Hello world Bye bye! 08:58am ccbsd3:readfile/> 10:18am ccbsd3:readfile/> cat -n f7.c 1 //f7.c -- by tsaiwn@csie.nctu.edu.tw 2 #include 3 int x, k; 4 long sum; 5 int main( ) { 6 FILE* fp; 7 fp=freopen("in.txt", "rt", stdin); // §ï±q in.txt Ū 8 if(fp==0) { perror("Open error."); exit(38); } 9 sum = k=0; 10 printf("x=? "); 11 scanf("%d", &x); 12 while( !feof(stdin) ) { 13 printf("Got %d\n", x); 14 ++k; // count 15 sum += x; 16 printf("x=? "); 17 scanf("%d", &x); 18 } 19 printf("Total %d numbers. Sum=%d\n", k, sum); 20 return 0; 21 } 10:18am ccbsd3:readfile/> gcc f7.c 10:18am ccbsd3:readfile/> ./a.out Open error.: No such file or directory 10:18am ccbsd3:readfile/> vi in.txt 10:18am ccbsd3:readfile/> cat in.txt 12 23 33 50 88 10:18am ccbsd3:readfile/> ./a.out x=? Got 12 x=? Got 23 x=? Got 33 x=? Got 50 x=? Got 88 x=? Total 5 numbers. Sum=206 10:18am ccbsd3:readfile/> exit