我编写的一个关于C语言文件操作的程序段,但是运行却得不到预期结果,调试过感觉是输入输出文件操作那个地方出错,但是却不知道错在哪里,请大家帮忙看下,谢谢了!!
其他操作函数我没写上,就下面这个程序段,大家帮忙看看!!
#include<stdio.h>
#include<stdlib.h>
struct student /* 学生档案 */
{ char num[10]; /* 学号 */
char name[12]; /* 姓名 */
char sex[4]; /* 性别 */
char tel[15]; /* 电话 */
char addr[50];
};
char filename[30]; /* 学生信息表名 */
FILE *fp;
void ListCreate(); /* 建立信息表 */
void ListAdd(); /* 添加 */
void ListSearch(); /* 查找 */
void ListModify(); /* 修改 */
void ListDelete(); /* 删除 */
void ListPrint(); /* 输出 */
void exit(); /* 退出 */
/*------------------------------------主函数----------------------------------------*/
void main()
{ struct student stu; /* 链表结构体变量*/
int n;
ListCreate();
while(1)
{ printf("\nAdd :(Please enter 1)");
printf("\nSearch:(Please enter 2)");
printf("\nUpdate:(Please enter 3)");
printf("\nDelete:(Please enter 4)");
printf("\nCount :(Please enter 5)");
printf("\nOrder :(Please enter 6)");
printf("\nOutput:(Please enter 7)");
printf("\nQuit :(Please enter 0)");
printf("\nPlease Choose:");
scanf("%d",&n);
if((n>=0)&&(n<=5))
{ switch(n)
{ /* case 1: ListAdd(); break; 添加 */
case 2: ListSearch(); break; /* 查找 */
case 3: ListModify(); break; /* 修改 */
case 4: ListDelete(); break; /* 删除 */
case 5: ListPrint(); break; /* 输出 */
case 0: exit(0);
}
printf("\n\nFinish!Please chose again...");
}
else
printf("\n\nFalse!Please chose again...");
}
}
/*--------------------------------创建学生资料----------------------------------*/
void ListCreate()
{ struct student stu;
char ch;
printf("\nPlease enter the name of the students information system:");
scanf("%s",filename);
if((fp=fopen(filename,"w"))==NULL)
{ printf("\nSorry,you couldn't create the students information system!");
exit(0);
}
fprintf(fp,"%-15s%-15s%-10s%-20s%-50s\n","NUM","NAME","SEX","TEL","ADDR");
printf("\nPlease enter number,name,sex,telephone and address(Enter 0 in the end)\n");
scanf("%s",stu.num);
getchar();
while(ch!='0')
{ scanf("%s",stu.name);
getchar();
scanf("%s",stu.sex);
getchar();
scanf("%s",stu.tel);
getchar();
scanf("%s",stu.addr);
getchar();
fprintf(fp,"%-15s%-15s%-10s%-20s%-50s%\n",stu.num,stu.name,stu.sex,stu.tel,stu.addr);
ch=getchar();
if(ch!='0')
{ scanf("%s",stu.num);
getchar();
}
}
fclose(fp);
}
/*-------------------------------显示输出学生资料-------------------------------*/
void ListPrint()
{ struct student stu;
if((fp=fopen(filename,"r"))==NULL)
{ printf("\nSorry,you can't open the students information system!");
exit(0);
}
printf("\n\n%40s\n\n","The Students Information System");
while(!feof(fp))
{
fscanf(fp,"%s",stu.num);
fscanf(fp,"%s",stu.name);
fscanf(fp,"%s",stu.sex);
fscanf(fp,"%s",stu.tel);
fscanf(fp,"%s",stu.addr);
printf("%-15s%-15s%-10s%-20s%-50s\n",stu.num,stu.name,stu.sex,stu.tel,stu.addr);
}
fclose(fp);
}