c语言怎么用文件保存和读取 结构体数组/

txt

#include <stdio.h>
int main()
{
struct test {
int a;
char s[10] ;
double d ;
} tr[3] , tw[3] ={
{1,"hello1" , 100 },
{2,"hello2" , 90},
{3,"hello3", 200}
} ; //定义一个结构体数组

FILE *fp ;
fp=fopen("struct.dat" , "wb" );
if ( fp == NULL )
return -1 ;
fwrite( (char*)tw , sizeof(struct test), 3 , fp ); //将数组写入文件
fclose(fp);
//以上完成写操作
fp=fopen("struct.dat" , "rb" );
if ( fp == NULL )
return -1 ;
fread( (char*)tr , sizeof(struct test), 3 , fp ); //从文件中读三个结构体的数据,也可以一个一个的读
fclose(fp);
//输出读到的数据
{
int i;
for(i=0;i<3;i++ )
printf("%d %s %lf\n" , tr[i].a , tr[i].s, tr[i].d );
}

return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-11-25
结构体数据的保存通常以二进制形式进行.
FILE *fw = fopen(filename,"wb");
写函数是fwrite(&structdata,sizeof(structdata),1,fw);
FILE *fr = fopen(filename,"rb");
读函数是fread(*structdata,sizeof(structdata),1,fr);
每次读写都是一个完整的结构体数据。本回答被提问者采纳
第2个回答  2013-07-10
文本方式读写
#include "stdio.h"
#include <stdlib.h>
#define SIZE 5
struct student{
char ID[10];
char Name[12];
int Score;
} stud[SIZE];

void read()
{
FILE *fp;
int i;

if((fp=fopen("score.txt","rt"))==NULL)
{
printf("cannot open file\n");
return;
}
for(i=0;i<SIZE;i++)
fscanf(fp,"%s %s %d\n",stud[i].ID,stud[i].Name,&stud[i].Score);
fclose(fp);
}

void save()
{
FILE *fp;
int i;
if((fp=fopen("score.txt","wt"))==NULL)
{
printf("cannot open file\n");
return;
}
for(i=0;i<SIZE;i++)
fprintf(fp,"%-10s%-12s%d\n",stud[i].ID,stud[i].Name,stud[i].Score);
fclose(fp);
}

void main()
{
read();
save();
}追问

&stud[i].Score 为什么它要加个&

追答

因为是整数(以及浮点数)

第3个回答  2013-07-10
fread/fwrite,里面是读取/写入块,一个块多少字节,你可以把一个块想象成为一个结构,数量就是数组
相似回答