文件读入和保存的问题,请高手帮忙看看,新人学习
#include<stdio.h>#include<stdlib.h>
#include<malloc.h>
#include<string.h>
#include<conio.h>
#define OK 1
#define null 0
#define error 0
#define OVERFLOW 0
#define LIST_INTT_SIZE 10000
#define LISTINCREMENT 10
struct student
{
char name[20];
long int number;
int age;
float score;
};
typedef int status;
typedef student elemtype;
typedef struct
{
elemtype *elem;
int length;
int listsize;
}sqlist;
status initlist_sq(sqlist &L)
{
L.elem=(elemtype*)malloc(1000*sizeof(elemtype));
if(!L.elem)
exit(OVERFLOW);
L.length=0;
L.listsize=LIST_INTT_SIZE;
return OK;
}
void datain_sq(sqlist &L)
{
long int num;
int i=0;
do /*输入学号*/
{
printf("请输入该学生的学号:(以输入0结束!)\n");
scanf("%ld",&num);
}while(num<0);
while(num!=0)
{
printf("请输入该学生的姓名:\n");
scanf("%s",L.elem[i].name);
printf("请输入该学生的年龄:\n");
scanf("%d",&L.elem[i].age);
printf("请输入该学生的总分:\n");
scanf("%f",&L.elem[i].score);
L.elem[i].number=num;
i++;
L.length++;
do
{
printf("请输入该学生的学号:(以输入0结束!)\n");
scanf("%ld",&num);
}while(num<0);
}
}
void fileread(sqlist &L)
{
char *filename;
filename=(char *)malloc(sizeof(char));
int i=0;
FILE *stu;
fflush(stdin);
printf("请输入你要读取文件的名字!\n");
gets(filename);
filename=strcat(filename,".txt");
stu=fopen("filename","r");
if(stu==NULL)
printf("文件中没有任何信息,请先存入信息!\n");
else
{
while(!feof(stu))
{
fscanf(stu,"%s%ld%d%.2f",L.elem[i].name,&L.elem[i].number,&L.elem[i].age,&L.elem[i].score);
i++;
L.length++;
}
}
fclose(stu);
}
void filesave(sqlist &L)
{
char *filename;
FILE *stu;
int i=0;
filename=(char *)malloc(sizeof(char));
fflush(stdin);
printf("请输入你要读取文件的名字!\n");
gets(filename);
filename=strcat(filename,".txt");
stu=fopen("filename","w");
do
{
fprintf(stu,"%s%ld%d%.2f",L.elem[i].number,L.elem[i].age,L.elem[i].score);
i++;
L.length--;
}while(L.length);
}
void main()
{
sqlist myL;
initlist_sq(myL);
int n;
printf("1.从键盘读入数据\n2.从文件读入数据\n3.保存数据到文件\n")
a:printf("请选择:");
scanf("%d",&n);
switch(n)
{
case 1: datain_sq(myL);break;
case 2: fileread(myL);break;
case 3: filesave(myL);break;
default : printf("输入错误");
}
goto a;
}
不知道错在哪里,请高手帮帮忙