900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > C语言文件读写(结构体文件)

C语言文件读写(结构体文件)

时间:2022-06-21 12:25:56

相关推荐

C语言文件读写(结构体文件)

有时候,我们需要将输入的数据存储起来,这时候就需要用到文件,对于C语言而言,文件的读写有多种方式,下面主要是结构体文件的读写,例如student.dat(第一列是学号,第二列是姓名)

0001 xiaoming0002 小明

1.定义结构体

//定义一个结构体typedef struct Student{int stu_id;char name[100];} Stu;

2.写数据

// 定义一个文件指针FILE *fp ;// 初始化一个结构体数组Stu stuw[2] = {{0001, "xiaoming" },{0002, "小明"}} ;// 打开文件,没有文件自动创建fp = fopen("student.dat","wb"); // b:表示以二进制写入// 写入数据fwrite( (char*)stuw,sizeof(Stu),2,fp); //2:表示将数组中两个元素写入文件// 关闭文件fclose(fp);

3.读数据

// 定义一个文件指针FILE *fp ;// 定义一个buf结构体,用于得到文件内容struct stat buf;// 定义一个文件行数记录变量int rows;// 定义一个Student结构体Stu stur[MAX]; // MAX通过#define设置为100// 求文件中的行数(记录个数)stat("student.dat",&buf);rows = buf.st_size/sizeof(Stu);// 打开文件fp = fopen("student.dat","rb");// 读取数据到数组中fread((char *)stur,sizeof(Stu),rows,fp);// 关闭文件fclose(fp);// 遍历数组,打印数据信息for(int i=0;i<rows;i++)printf("%d\t%s\n",stur[i].stu_id,stur[i].name);

具体demo.c

#include <stdio.h>#include <sys/types.h>#include <sys/stat.h>#define MAX 100//定义一个结构体typedef struct Student{int stu_id;char name[100];} Stu;int main(int argc, char const *argv[]) {/* code */// 声明函数void Write();void Read();// 函数调用 Write();Read();return 0;}/* 数据写入文件 */void Write(){// 定义一个文件指针FILE *fp ;// 初始化一个结构体数组Stu stuw[2] = {{0001, "xiaoming" },{0002, "小明"}} ;// 打开文件,没有文件自动创建fp = fopen("student.dat","wb"); // b:表示以二进制写入// 写入数据fwrite( (char*)stuw,sizeof(Stu),2,fp); //2:表示将数组中两个元素写入文件// 关闭文件 fclose(fp);}// 文件数据读取void Read(){// 定义一个文件指针FILE *fp ;// 定义一个buf结构体,用于得到文件内容struct stat buf;// 定义一个文件行数记录变量int rows;// 定义一个Student结构体 Stu stur[MAX];// 求文件中的行数(记录个数)stat("student.dat",&buf);rows = buf.st_size/sizeof(Stu);// 打开文件fp = fopen("student.dat","rb");// 读取数据到数组中fread((char *)stur,sizeof(Stu),rows,fp);// 关闭文件 fclose(fp);// 遍历数组,打印数据信息for(int i=0;i<rows;i++)printf("%d\t%s\n",stur[i].stu_id,stur[i].name);}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。