zoukankan      html  css  js  c++  java
  • C语言:将结构体存放到文件中

    #include <stdio.h>
    #include <stdlib.h>
    #define MAXTLEN 70
    #define MAXALEN 70
    #define MAXBKS 10
    struct book{
            char title[MAXTLEN];
            char author[MAXALEN];
            float value;
    };
    
    int main(){
            struct book library[MAXBKS];    //图书馆
            int count = 0, index, filecount;
            int size = sizeof(struct book); //这点值得注意
            FILE *pbooks;
            if((pbooks = fopen("book.dat","a+b")) == NULL){
                    fputs("Can not open book.dat file
    ", stderr);
                    exit(1);
            }
            rewind(pbooks);
            while(count < MAXBKS && fread(&library[count],size,1,pbooks) == 1){
                    if(count == 0){
                            puts("Current contents of book.dat: ");
                    }
                    printf("%s by %s: $%.2f
    ",library[count].title,library[count].author,library[count].value);
                    count++;
            }
            filecount = count;
            if(count == MAXBKS){
                    fputs("The book.dat file is full",stderr);
                    exit(2);
            }
            puts("please add the new book, title:");
            while(count < MAXBKS && gets(library[count].title) != NULL && library[count].title[0] != ''){
                    puts("the author:");
                    gets(library[count].author);
                    puts("the value:");
                    scanf("%f",&library[count++].value);
                    while(getchar() != '
    '){
                            continue;
                    }
                    if(count < MAXBKS){
                            puts("---continue---");
                    }
            }
            if(count > 0){
                    puts("Here is the list of your books:");
                    for(index = 0; index<count; index++){
                            printf("%s by %s: $%.2f
    ",library[index].title,library[index].author,library[index].value);
                    }
                    fwrite(&library[filecount],size,count-filecount,pbooks);
            }else{
                    puts("No books? Too bad
    ");
            }
            puts("Bye
    ");
            fclose(pbooks);
            return 0;
    }
    Current contents of book.dat: 
    C语言权威指南 by jimmy: $68.00
    PHP项目大全 by jimmy: $99.90
    please add the new book, title:
  • 相关阅读:
    C#基础知识简单梳理
    knearest neighbor
    二叉查找树的实现
    Unix/Linux 那些系统启动后的进程
    Nginx反向代理IIS
    线程漫谈——线程同步之信号量和互斥量
    BtxCMS@B.T.X 项目及界面展示 [下载]
    MVC in MFC or WTL
    HTTP HTTPS WebService
    ASP.NET WebAPI RC 竟然不支持最常用的json传参
  • 原文地址:https://www.cnblogs.com/bai-jimmy/p/4470807.html
Copyright © 2011-2022 走看看