如何從一個文本文件中讀入信息,并建立鏈表啊? 比如:從文件INA。TXT讀入學生信息,建立鏈表A,從文件INB。TXT讀入學生信息,建立鏈表B,其中每個鏈表中結點包括學號,姓名,成績將兩個鏈表合并到A,按學號升序排列,最后將鏈表A中的學生信息輸出到文件OUT。TXT中。 該怎么辦啊?
熱心網友
呵呵,好久沒編了,都忘光了,重新復習一下。為簡單計,只作出 【鏈表←→文件】 雙向的讀寫,而鏈表的排序簡單、基本,在此省略?!境绦虿襟E】:ina。txt↘ 鏈表→不排序,直接輸出到屏幕→輸出到Out。txtinb。txt↗【最為關鍵的地方】:"%20d%20s%20d"鏈表以如上格式保存、讀寫到文件。很好理解,以“學號20位,姓名20、成績20”的格式進行讀寫?!菊{試環境】:Visual C++ 6。0 英文企業版并在“Borland C++ 5。5 編譯器 For DOS”測試通過Win XP SP2中文版【附件】:ina。txt ↘inb。txt 一→ 打包成附件。RaRTest。cpp ↗【源程序】:#include #include //#include #define NULL 0#define FORMAT "%20d%20s%20d"#define LEN sizeof(student)struct student{int number; /*學號*/char name[10]; /*姓名*/int score; /*成績*/struct student *pNext;};void main(){FILE *fposition = NULL;student *pOne = NULL, *pTwo = NULL, *pHead = NULL;_flushall();// 以下代碼打開ina。txt,并讀入鏈表if ((fposition = fopen ("ina。txt", "r")) == NULL){printf("\n打開文件失敗\n");exit(0);}pOne = (student *) malloc(LEN);pTwo = pOne;pHead = pOne;pHead-pNext = NULL;while (!feof(fposition)){if (!fscanf(fposition, FORMAT, &pOne-number, &pOne-name, &pOne-score))printf("\n讀入文件出錯,可能文件為空,或文件不存在!\n");pTwo = pOne;pOne = (student *) malloc(LEN);pTwo-pNext = pOne; }// 以下代碼打開inb。txt,追加到鏈表if ((fposition = fopen ("inb。txt", "r")) == NULL){printf("\n打開文件失敗\n");exit(0);}while (!feof(fposition)){if (!fscanf(fposition, FORMAT, &pOne-number, &pOne-name, &pOne-score))printf("\n讀入文件出錯,可能文件為空,或文件不存在!\n");pTwo = pOne;pOne = (student *) malloc(LEN);pTwo-pNext = pOne; }pTwo-pNext = NULL;pOne = pHead;// 以下代碼輸出鏈表,并保存到Out。txtif(pOne == NULL){printf("\n數據為空!\n");}else{printf("\t\t學號\t\t姓名\t\t\t成績\n");if ((fposition = fopen ("out。txt", "w")) == NULL){printf("\n打開文件失敗\!n");exit(0);}while (pOne != NULL){printf(FORMAT, pOne-number, pOne-name, pOne-score);printf("\n");if (! fprintf(fposition, FORMAT, pOne-number, pOne-name, pOne-score)){printf("\n讀入文件出錯!\n");}pOne = pOne-pNext; }fclose(fposition);free(pOne); /*釋放*/pOne = NULL;free(pTwo); /*釋放*/pTwo = NULL;free(pHead); /*釋放*/pHead = NULL;}}。