109,345
社区成员




结构体是自学的,不知道为什么结果就是不输出〒▽〒
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define SIZE 100
struct Student
{
char studentnum[11];
char name[3];
char major;
int year;
char sex;
int score;
}stud[SIZE]={'\0'};
void print(char *file)
{
FILE *fp;
int i;
fp=fopen(file,"r");
for(i=0;i<SIZE;i++)
{
fread(&stud[i],sizeof(struct Student),1,fp);
printf("%-12s%-5s%-12s%-5d%-2s%-3d",stud[i].studentnum,stud[i].name,stud[i].major,stud[i].year,stud[i].sex,stud[i].score);
}
fclose(fp);
}
int main()
{
FILE *fp;
char filename[100];
int choice;
printf("请输入数据文件名:");
scanf("%s",filename);//从键盘读取文件名存入字符数组filename
getchar();//消化回车
if((fp=fopen(filename,"r"))==NULL)//只读模式打开文件并使fp指向此文件
{
printf("文件不存在,请重新运行此程序\n");//若打开出错则退出程序
exit(0);
}
print(filename);
return 0;
}
在代码中,从键盘输入数据文件的名称,并尝试以只读模式打开该文件。如果文件不存在或打开文件时出现错误,程序将输出错误消息并退出。请确保输入的文件名正确,并且确保该文件存在于当前工作目录中。代码中的print函数尝试从数据文件中读取struct Student的数据,如果数据文件中的内容不符合结构体的定义,也可能导致数据读取失败或输出不正确。