我試圖在C中製作一個程序,用於跟蹤學生借閱的書籍。我很難在訪問文件指針。當我使用文件時,我通常不會使用fscanf(),而是使用通常的scanf。我有這樣的數據結構:C中的文件,訪問指針,讀取和寫入文件
typedef struct{ char fName[24], mInitial, lName[16]; }nameType; typedef struct{ unsigned long idNo; nameType studName; char course[8]; int yrLevel; books borrowedBooks; int bksCtr; }student; typedef struct{ student *studs; int studCtr; }studList;
我已經創建了兩個功能,截至目前,這是addStudToFile(無效),增加了學生的文件,displayStudsFromFile(無效),基本打印出在文件中添加的學生。這是我的新手功能代碼:
void addStudToFile(void) { FILE *fp; studList myStud; fp = fopen("students.db", "w"); if(fp!=NULL){ /* ask for student details and adds these to the file */ printf("Enter ID number: "); fflush(stdin); scanf(,"%lu", &myStud.studs->idNo); printf("Enter First Name: "); fflush(stdin); gets(myStud.studs->studName.fName); printf("Enter Last Name: "); fflush(stdin); gets(myStud.studs->studName.lName); printf("Enter Middle Initial: "); fflush(stdin); scanf("%c", &(myStud.studs->studName.mInitial)); printf("Enter Course: "); fflush(stdin); gets(myStud.studs->course); printf("Enter Year: "); fflush(stdin); scanf("%d", &(myStud.studs->yrLevel)); fwrite(&myStud, sizeof(studList),1,fp); fclose(fp); } }
和
void displayStudsFromFile(void) { FILE *fp; studList myStud; fp = fopen("students.db", "r"); if(fp!=NULL){ while (fread(&myStud, sizeof(studList), 1, fp)){ printf("%lu\t %s, %s %s\t %s-%d", myStud.studs->idNo, myStud.studs->studName.lName, myStud.studs->studName.fName, myStud.studs->studName.mInitial, myStud.studs->course, myStud.studs->yrLevel); printf("borrowed %d books", myStud.studs->bksCtr); } fclose(fp); } }
現在,我在這裏的問題是,在我的訪問列表是myStud。在我的addStudToFile()函數,每次我輸入我的ID號,我的程序停止工作。爲什麼它停止工作?我需要malloc嗎?或者是我在訪問scanf()錯?我遇到我的程序停止再次工作的另一種情況是當我打電話給我的顯示功能時。它顯示的東西,但外星人/垃圾值。
這是在哪裏我在掃描功能遇到我的問題的屏幕截圖:
這裏是我的顯示功能:
我希望有人能夠幫助我與此。謝謝!
不要對發佈圖片感覺不好 - 這是一個純文本程序,對吧?圖像會添加什麼? – usr2564301 2014-12-02 22:02:26
寧可截圖。我很抱歉,我已經編輯過了。謝謝! @Jongware – 2014-12-02 22:04:24
這一行:while(fread(&myStud,sizeof(studList),1,fp)){在到達文件結束時不一定會停止。因爲它可以返回除'1'之外的其他數字,例如在某些錯誤情況下不爲0。建議:while(1 == fread(&myStud,sizeof(studList),1,fp))){ – user3629249 2014-12-03 04:09:42