【发布时间】:2018-11-21 16:32:45
【问题描述】:
这是我的代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct student
{
char studentName[50];
int id;
};
struct student_detail
{
int day, month, year, grade;
struct student information;
}stu_data;
//---------------------------------//
int main()
{
struct student_detail stu_data[10];
int student_no, i=0, choice=0;
char keyword[50];
FILE *fptr;
printf("Add-Information(1) || Get-Information(2): ");
scanf("%d",&choice);
if(choice == 1){
fptr = (fopen("userInfo.txt","ab"));
system("CLS");
printf("How many students would you like to add?[MAX 10]: ");
scanf("%d",&student_no);
system("CLS");
for(i=0; i < student_no; i++){
system("CLS");
printf("Enter student#%d's name: ",i+1);
scanf("%s", stu_data[i].information.studentName);
printf("\nWhat is %s's studentID?: ",stu_data[i].information.studentName);
scanf("%d",&stu_data[i].information.id);
printf("\nWhat is %s's date of birth?(dd/mm/yy):\n",stu_data[i].information.studentName);
scanf("%d %d %d",&stu_data[i].day, &stu_data[i].month, &stu_data[i].year);
fwrite(&stu_data[i].information.studentName, sizeof(struct student), 1, fptr);
fwrite(&stu_data[i].information.id, sizeof(struct student), 1, fptr);
fwrite(&stu_data[i].day, sizeof(struct student), 1, fptr);
fwrite(&stu_data[i].month, sizeof(struct student), 1, fptr);
fwrite(&stu_data[i].year, sizeof(struct student), 1, fptr);
}
fclose(fptr);
}
if(choice == 2){
fptr = (fopen("userInfo.txt","rb+"));
system("CLS");
printf("What students information would you like to retreive?: ");
scanf("%s",keyword);
fseek(fptr, sizeof(struct student), SEEK_SET);
fread(&stu_data[i].information.studentName, sizeof(struct student), 1, fptr);
fread(&stu_data[i].information.id, sizeof(struct student), 1, fptr);
fread(&stu_data[i].day, sizeof(struct student), 1, fptr);
fread(&stu_data[i].month, sizeof(struct student), 1, fptr);
fread(&stu_data[i].year, sizeof(struct student), 1, fptr);
printf("Name: %s",stu_data[i].information.studentName);
printf("\nID: %d",stu_data[i].information.id);
printf("\nDate of birth: %d/%d/%d\n\n",stu_data[i].day, stu_data[i].month, stu_data[i].year);
system("PAUSE");
fclose(fptr);
return 0;
}
}
文件的输入如下所示:
姓名:莱利
编号:1
出生日期:01/10/2001
当我从文件中读取信息时,我得到了正确的信息,但不是全部,当我读到消息时,如下所示:
姓名:y
编号:1
出生日期:10/2001/2686248
写作工作只是不阅读(抱歉程序中缺少 cmets)。
【问题讨论】:
-
请提供每次使用scanf的返回值。不是扫描的值,是返回的值,表示扫描成功的次数。
-
为什么每个
fread的大小都是sizeof(struct student)? -
fwrite(&stu_data[i], sizeof(stu_data[i]), 1, fptr);是将一个条目写入文件的正确方法。阅读也一样。