我正在尝试使用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()访问方式不对?另一个情况是,当我调用我的显示函数时,我再次遇到了程序停止工作的情况。它会显示一些奇怪/垃圾值。
这里是我在扫描函数中遇到问题的屏幕截图:
这是我的显示函数:
希望有人能帮助我解决这个问题。谢谢!