首页 > 代码库 > c语言----程序记录
c语言----程序记录
1.结构体写入文件,读取
#include <stdio.h>#include <string.h>#include <stdlib.h> #define max 5struct books{ char title[20]; char author[20]; int price;};const char * fileName="books.txt";int size=sizeof(struct books);void read(struct books bks[]);void write(struct books bks[]);void list(struct books bks[]);void demo(struct books bks[]);void main(void){ struct books bks[max]; //write(bks); read(bks);}void write(struct books bks[]){ FILE * fp; int i=0; int addList; if((fp=fopen(fileName,"a+b")) == NULL) { printf("file open fail"); } puts("大侠,你想添加几条数据?"); scanf("%d",&addList); if(addList>0) { do{ printf("please add new book title\n"); scanf("%s",&bks[i].title); printf("please add new book author\n"); scanf("%s",&bks[i].author); printf("please add new book price\n"); scanf("%d",&bks[i].price); i++; fwrite(&bks[i],size,1,fp); }while(i<addList); } }void read(struct books bks[]){ FILE * fp; int i=0; if((fp=fopen(fileName,"r+")) == NULL) { printf("file open fail"); } rewind(fp); while( i<max && fread(&bks[i],size,1,fp) == 1) { printf("title is %s,author is %s,price is %d\n",bks[i].title,bks[i].author,bks[i].price); i++; } }
c语言----程序记录
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。