文件输入输出的问题
#include<stdio.h>#include<stdlib.h>
#include<string.h>
#define XS 5
struct Student
{
int xuehao;
char xingming[10];
int yuwen;
int shuxue;
int yingyu;
int pingjun;
}xuesheng[XS];
void paixu(struct Student a[], int n)
{
int i, j;
for(i = 0; i < XS - 1; i++)
{
for(j = i + 1; j < XS; j++)
{
if(a[i].pingjun > a[j].pingjun)
{
struct Student b;
b.xuehao = a[i].xuehao;
strcpy(b.xingming, a[i].xingming);
b.yuwen = a[i].yuwen;
b.shuxue = a[i].shuxue;
b.yingyu = a[i].yingyu;
b.pingjun = a[i].pingjun;
a[i].xuehao = a[j].xuehao;
strcpy(a[i].xingming, a[j].xingming);
a[i].yuwen = a[j].yuwen;
a[i].shuxue = a[j].shuxue;
a[i].yingyu = a[j].yingyu;
a[i].pingjun = a[j].pingjun;
a[j].xuehao = b.xuehao;
strcpy(a[j].xingming, b.xingming);
a[j].yuwen = b.yuwen;
a[j].shuxue = b.shuxue;
a[j].yingyu = b.yingyu;
a[j].pingjun = b.pingjun;
}
}
}
}
void ceshi(void) //用这个函数测试读取文件失败,但是我重新写了一个cpp文件测试却是成功的.高手来解答下.
{
struct Student
{
int xuehao;
char xingming[10];
int yuwen;
int shuxue;
int yingyu;
int pingjun;
}xue[XS];
FILE *fp;
if((fp = fopen("stu_sort.dat","rb")) == NULL)
{
printf("打开文件失败.\n");
exit(0);
}
for(int i = 0; i < XS; i++)
{
if(fread(&xue[i],sizeof(xue[i]), 1, fp) != 1)
{
printf("xue[%d]提取数据失败.\n",i);
}
}
for(int i = 0; i < XS; i++)
printf("学号:%d, 姓名:%-6s, 语文成绩:%d, 数学成绩:%d, 英语成绩:%d, 平均分:%d.\n",xue[i].xuehao,xue[i].xingming,xue[i].yuwen,xue[i].shuxue,xue[i].yingyu,xue[i].pingjun);
fclose(fp);
}
int main()
{
FILE *fp;
if((fp = fopen("stud.dat", "rb")) == NULL)
{
printf("打开文件失败.\n");
exit(0);
}
for(int i = 0; i < XS; i++)
{
if(fread(&xuesheng[i], sizeof(xuesheng[i]), 1, fp) != 1)
{
printf("读取文件数据失败.\n");
}
}
for(int i = 0; i < XS; i++)
printf("学号:%d, 姓名:%-6s, 语文成绩:%d, 数学成绩:%d, 英语成绩:%d, 平均分:%d.\n",xuesheng[i].xuehao,xuesheng[i].xingming,xuesheng[i].yuwen,xuesheng[i].shuxue,xuesheng[i].yingyu,xuesheng[i].pingjun);
paixu(xuesheng, XS);
fclose(fp);
if((fp = fopen("stu_sort.dat", "wb")) == NULL)
{
printf("打开文件失败.\n");
exit(0);
}
for(int i = 0; i < XS; i++)
{
if(fwrite(&xuesheng[i], sizeof(xuesheng[i]), 1, fp) == 1)
{
printf("xuesheng[%d]数据拷贝成功.\n",i);
}
}
ceshi();
fclose(fp);
system("pause");
return 0;
}