数据结构中能将一个结构体结点存入数组里吗?

类似typedef struct arcnode{
int date;
struct arcnode *next;
}
然后将这样的结点存入一个AdjList[]数组中

把一个结构体数组写入文件分三步:
1、以二进制写方式(wb)打开文件
2、调用写入函数fwrite()将结构体数据写入文件
3、关闭文件指针
相应的,读文件也要与之匹配:
1、以二进制读方式(rb)打开文件
2、调用读文件函数fread()读取文件中的数据到结构体变量
3、关闭文件指针
参考代码如下:
#include<stdio.h>
struct stu {
char name[30];
int age;
double score;
};
int read_file();
int write_file();
int main()
{
if ( write_file() < 0 ) //将结构体数据写入文件
return -1;
read_file(); //读文件,并显示数据
return 0;
}

int write_file()
{
FILE *fp=NULL;
struct stu student={"zhang san", 18, 99.5};
fp=fopen( "stu.dat", "wb" ); //b表示以二进制方式打开文件
if( fp == NULL ) //打开文件失败,返回错误信息
{
printf("open file for write error\n");
return -1;
}
fwrite( &student, sizeof(struct stu), 1, fp ); //向文件中写入数据
fclose(fp);//关闭文件
return 0;
}

int read_file()
{
FILE *fp=NULL;
struct stu student;
fp=fopen( "stu.dat", "rb" );//b表示以二进制方式打开文件
if( fp == NULL ) //打开文件失败,返回错误信息
{
printf("open file for read error\n");
return -1;
}
fread( &student, sizeof(struct stu), 1, fp ); //读文件中数据到结构体
printf("name=\"%s\" age=%d score=%.2lf\n", student.name, student.age, student.score ); //显示结构体中的数据
fclose(fp);//关闭文件
return 0;
}
温馨提示:答案为网友推荐,仅供参考
相似回答