fread从txt中读取信息到结构体数组,但是在另一个函数再次输出结构体数组信息却为空
读取函数:
输出函数:
调用部分:
运行结果:
源码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 20
FILE *fp=NULL;//定义文件指针
struct Student{
int id;
char name[10];
double score;
};
struct Student stu[N];
struct Student buffer;
void fwrite_to_file(){
fwrite(&buffer,sizeof(struct Student),1,fp);
//memset(&buffer,0,sizeof(buffer));
//printf("%d,%s,%lf\n",stu[index].id,stu[index].name,stu[index].score);
}
void fread_file(){
memset(&buffer,0,sizeof(buffer));
//fseek(fp,0,SEEK_SET);
fread(&buffer,sizeof(struct Student),1,fp);
puts("fread_file sucucess");
}
int fopen_file_null(){
fp=fopen("./test1.txt","w+");//以读写方式打开文件,若不存在则创建,写之前将文件清空;成功的话将返回文件指针
if(fp==NULL){
perror("fopen err");//打开文件失败
return 0;
}
else{printf("打开文件成功\n");}
}
int fopen_file_append(){
fp=fopen("./test1.txt","a+");//打开文件用于追加,若不存在则创建,读文件时从文件初始开始,输出时追加到末尾
if(fp==NULL){
perror("fopen err");//打开文件失败
return 0;
}
else{printf("打开文件成功\n");}
}
void addstu_append(){
fopen_file_append();
memset(&buffer,0,sizeof(buffer));
puts("please input one stu's message:id(int) name(string) score(double)");
scanf("%d %s %lf",&buffer.id,buffer.name,&buffer.score);
fwrite_to_file();
fclose(fp);
}
int file_to_stu(){
//fopen_file_append();
fp=fopen("./test1.txt","r");
//fseek(fp,0,SEEK_SET);
int index=0;
while(!feof(fp)){
//fread_file();
fread(&stu[index],sizeof(struct Student),1,fp);
printf("%d %s %lf",stu[index].id,stu[index].name,stu[index].score);
//fread(&stu[index].id,sizeof(int),1,fp);
//fread(&stu[index].name,sizeof(stu[0].name),1,fp);
//fread(&stu[index],sizeof(double),1,fp);
//stu[index].id=buffer.id;
//strcpy(stu[index].name,buffer.name);
//stu[index].score=buffer.score;
//printf("%d %s %lf",buffer.id,buffer.name,buffer.score);
//memset(&buffer,0,sizeof(buffer));
index++;
printf("index=%d\n",index);
}
return index-1;
}
void outputstu(int index){
for(int i=0;i<index;i++){
printf("%d %s %lf",stu[index].id,stu[index].name,stu[index].score);
printf("\n");
}
}
int main(){
int choice;
int index=0;
loop:
puts("please input your choice:");
puts("1.追加学生 2.输出所有学生信息");
scanf("%d",&choice);
switch(choice){
case 1:
addstu_append();goto loop;
case 2:
index=file_to_stu();
outputstu(index);
goto loop;
default:
break;
}
fclose(fp);
fp=NULL;
return 0;
}