- nicehost
-
#include<stdio.h>
struct student
{char name[20];
float heigh;
float weight;
}s[5];
void main()
{
int i;
struct student *p1,*p2;/*定义两个结构体指针*/
FILE *fp;
printf("plaese input students"information: ");
for(i=0;i<5;i++) /*依次输入五个学生信息*/
scanf("%s%f%f",s[i].name,&s[i].heigh,&s[i].weight);
fp=fopen("/home/ccx/mydocument/stu.dat","wb+");/*为读写建立一个二进制文件stu.dat*/
for(i=0;i<5;i++)
if(fwrite(&s[i],sizeof(struct student),1,fp)!=1)
printf("file write error! ");
fp=fopen("/home/ccx/mydocument/stu.dat","rb+");/*打开该二进制文件*/
for(i=0,p1=s,p2=s;i<5;i++)
{fread(&s[i],sizeof(struct student),1,fp);/*依次读取信息*/
if((p1+i)->heigh>p1->heigh) p1=p1+i;/*若后一个学生身高比前一个高,互换*/
if((p2+i)->weight>p2->weight) p2=p2+i;/*若后一个学生体重比前一个重,互换*/
}
printf("身高最高的是:%s %f %f ",p1->name,p1->heigh,p1->weight);/*输出最高者*/
printf("体重最重的是:%s %f %f ",p2->name,p2->heigh,p2->weight);/*输出最重者*/
fclose(fp);
}
运行结果:
plaese input students"information:
li 165 58
hu 190 65
she 178 64.5
he 174 62
wang 178 67
身高最高的是:hu 190.000000 65.000000
体重最重的是:wang 178.000000 67.000000
- wio
-
第一题:
#include<stdio.h>
#define FILENAME "C:\stu.dat"
struct tag_std
{
unsigned int height;
unsigned int weight;
char name[12];
};
typedef struct tag_std STD;
int main()
{
FILE *fp;
STD student[5];
int i;
printf("Please input five students" information "
"student"s name , height and weight: ");
for(i=0;i<5;i++)
{
printf("Student[%d]:",i+1);
scanf("%s%d%d",student[i].name,&student[i].height,&student[i].weight);
}
fp = fopen(FILENAME,"wb");
if(fp == NULL)
{
printf("ERROR in opening file! Pass any key to exit.");
getchar();
exit(0);
}
for(i=0;i<5;i++)
{
fprintf(fp,"%s %d %d ",student[i].name,student[i].height,student[i].weight);
}
}
----------------------------------------------------------------------------------------------------------------------
第二题:
#include<stdio.h>
#define FILENAME "C:\stu.dat"
struct tag_std
{
int height;
int weight;
char name[12];
};
typedef struct tag_std STD;
int main()
{
FILE *fp;
STD std[5];
int i;
fp = fopen(FILENAME,"rb");
if(fp == NULL)
{
printf("ERROR in opening file! Pass any key to exit.");
getchar();
exit(0);
}
for(i=0;i<5;i++)
{
fscanf(fp,"%s %d %d",std[i].name,&std[i].height,&std[i].weight);
}
for(i=0;i<5;i++)
{
printf("Student[%d]:",i+1);
printf("%s %d %d ",std[i].name,std[i].height,std[i].weight);
}
}
- LuckySXyd
-
楼主可以先编写一下,之后我给你修改一下,看一下你的问题所在,我感觉比直接给你好