//hwk11.c --- sample program to read studat.txt //========== by tsaiwn@csie.nctu.edu.tw // You have to modify this program to do the homework #include #include #include char* fileName = "studat.txt"; void test( ); void sort( ); // your sorting program void print( ); // 用來印出資料, 但只印出一部份! int main( ) { long long tStart, tStop; double tRun; test( ); // 讀取檔案到記憶體 // 算出每個人的學期總成績 printf("Before sort...\n"); print( ); // 叫用 print( ) 印出部份資料 tStart = clock( ); sort( ); // 叫用 你的 sort 程式 tStop = clock( ); tRun = 1.0*(tStop - tStart)/CLOCKS_PER_SEC; printf("...Sorting done in %.5f seconds.\n", tRun); printf("After sort...\n"); print( ); // 叫用 print( ) 印出部份資料 // Extra credit: 要有名次, 同分者比期末考, 再同比期中考, .. fprintf(stderr, "Hit ENTER key..."); getchar( ); return 0; } void print( ) { // 要用 Global 或是用傳參數的方式自行決定 // 印出前面 10 筆 // 印出 " ... " // 印出最後 10 筆 } void sort( ) { // 要用 Global 或是用傳參數的方式自行決定 // insertion sort, selection sort, bubble sort, quick sort ... int i, j, k, gg; // 寫好後請把下列 comment 掉 // for(i=1; i<= 35789999; ++i) for(k=1; i<= 999999; ++i) gg= gg*time(0); } /// do NOT modify the following code void test( ) { long id; char name[9]; int s1, s2, s3, s4, kk; char buf[99]; FILE* fp; fp = fopen(fileName, "rt"); if(fp==0) { fprintf(stderr, "File %s NOT found!\n", fileName); exit(38); } fgets(buf, sizeof(buf), fp); // stdin if(feof(fp) ) { fprintf(stderr, "EOF encounted.\n"); return; } fprintf(stderr, "Line-1: %s\n", buf); fgets(buf, sizeof(buf), fp); // stdin fprintf(stderr, "Line-2: %s\n", buf); s1=s2=s3=s4=0; kk = sscanf(buf,"%ld %s %d %d %d %d", &id, name, &s1, &s2, &s3,&s4); printf("kk=%d\n", kk); printf("id=%ld name = %s\n", id, name); printf("score= %d %d %d %d\n", s1, s2, s3, s4); fprintf(stderr, " counting..."); fflush(stderr); kk = 2; // already read 2 records while(! feof(fp) ) { buf[0] = 0; fgets(buf, sizeof(buf), fp); if( feof(fp) ) { // EOF 也可能有讀到不完整的 Line if(buf[0] == 0) break; // 沒有讀到啦 } ++kk; // got one record } fprintf(stderr, " .. done.\nTotal %d records in file %s\n", kk, fileName); fflush(stderr); fclose(fp); // close the file return; }