c语言对结构体的读取与写入
2017-08-14 19:35
162 查看
#include <stdio.h> #define SAVE_PATH "./student.data" typedef struct student { char name[10]; int id; char addr[20]; }student; void write_msg(const student* s,int len) { #define _BIN_WR FILE* fp; int i = 0; #ifdef _BIN_WR fp = fopen(SAVE_PATH,"rb+"); if(NULL == fp) { fp = fopen(SAVE_PATH,"wb+"); } fseek(fp,0,SEEK_END); while(i<len) { fwrite(s+i,sizeof(student),1,fp); i++; } #else fp = fopen(SAVE_PATH,"r+"); if(NULL == fp) { fp = fopen(SAVE_PATH,"w+"); } fseek(fp,0,SEEK_END); while(i<len) { fprintf(fp,"%-7s%-3d%-7s\n",(s+i)->name,(s+i)->id,(s+i)->addr); i++; } #endif fclose(fp); } void read() { FILE* fp; student s; #ifdef _BIN_WR fp =fopen(SAVE_PATH,"rb"); if(NULL == fp) { perror("open fail"); return; } while(1==fread(&s,sizeof(student),1,fp)) { printf("%s %d %s\n",s.name,s.id,s.addr); } #else fp = fopen(SAVE_PATH,"r"); if(NULL == fp) { perror("open fail"); } while(!feof(fp)) { fscanf(fp,"%s %d %s\n",s.name,&s.id,s.addr); printf("%s %d %s\n",s.name,s.id,s.addr); } #endif fclose(fp); } int main() { student s[2]={{"ylk",111,"wuhan"},{"ylk2",222,"wuhan"}}; write_msg(s,2); read(); return 0; }
相关文章推荐
- C语言中结构体写入文件中,再从文件中读取,更新文件等
- c语言学习之基础知识点介绍(十七):写入读取结构体、数组、结构体数组
- C++ txt 文件读取,并写入结构体中
- C语言中对文件最基本的读取和写入函数
- C语言读取文件数据到结构体数组
- C语言中文件的读取和写入
- 用C语言创建文件写入并读取
- c语言中往缓存写入结构体的方法
- C语言文件写入结构体的乱码解决方法
- C语言实现<读取>和<写入> *.ini文件。
- 定义一个学生结构体类型struct student,里边含有学号,姓名,分数,定义结构体数组struct student s[3],给数组赋初值后, 写入文件,然后通过lseek偏移到开头,然后再读取
- 【C语言】文件读取写入信息(二进制方式)
- c语言创建写入和读取TXT文件数据
- C语言读取输入的字符并写入到文件中
- C语言中打开文件读取,写入的操作
- C语言逐行读取文件内容,写入另外一个文件
- 【C语言】逐行读取文本数字数据,经过某种处理再逐行写入另外一个文本
- C语言向文件写入内容并读取显示
- iOS基础知识:文件流写入读取结构体变量、数组、结构体数组
- c语言实现读取txt文件内容到结构体数组中