标签:style blog io color ar sp 文件 数据 div
1.结构体写入文件,读取
#include <stdio.h> #include <string.h> #include <stdlib.h> #define max 5 struct 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++; } }
标签:style blog io color ar sp 文件 数据 div
原文地址:http://www.cnblogs.com/hanyouchun/p/4079124.html