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

txt
2025-03-13 08:18:56
推荐回答(4个)
回答1:

#include
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;
}

回答2:

结构体数据的保存通常以二进制形式进行.
FILE *fw = fopen(filename,"wb");
写函数是fwrite(&structdata,sizeof(structdata),1,fw);
FILE *fr = fopen(filename,"rb");
读函数是fread(*structdata,sizeof(structdata),1,fr);
每次读写都是一个完整的结构体数据。

回答3:

文本方式读写
#include "stdio.h"
#include
#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 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 fprintf(fp,"%-10s%-12s%d\n",stud[i].ID,stud[i].Name,stud[i].Score);
fclose(fp);
}

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

回答4:

fread/fwrite,里面是读取/写入块,一个块多少字节,你可以把一个块想象成为一个结构,数量就是数组