我试图在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