【发布时间】:2015-01-31 07:28:36
【问题描述】:
我正在尝试用 C 语言编写一个程序来跟踪学生借阅的书籍。我很难用文件访问指针。当我使用文件时,我通常不使用 fscanf(),而是使用通常的 scanf。我有这个数据结构:
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(void),它将学生添加到文件中,另一个是 displayStudsFromFile(void),它基本上打印出文件中添加的学生。这些是我的新手功能代码:
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() 中的访问有误?我遇到我的程序再次停止工作的另一种情况是当我调用我的显示函数时。它显示了一些东西,但是外星人/垃圾值。
这是我在扫描功能中遇到问题的屏幕截图:
这是我的显示功能:
我希望有人可以帮助我解决这个问题。谢谢!
【问题讨论】:
-
不要因为不发布图片而感到难过——这是一个纯文本程序,对吧?图片会添加什么?
-
截图。对不起,我已经编辑过了。谢谢! @Jongware
-
这一行:while (fread(&myStud, sizeof(studList), 1, fp)){ 到达文件末尾时不一定会停止。因为它可以返回除 '1' 之外的其他数字,例如在某些错误条件下不为 0。建议:while (1 == fread(&myStud, sizeof(studList), 1, fp)) ) {
标签: c file function pointers structure