码迷,mamicode.com
首页 > 编程语言 > 详细

c语言----程序记录

时间:2014-11-06 17:22:56      阅读:155      评论:0      收藏:0      [点我收藏+]

标签: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++;
    }
        
}

 

c语言----程序记录

标签:style   blog   io   color   ar   sp   文件   数据   div   

原文地址:http://www.cnblogs.com/hanyouchun/p/4079124.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!