C語言:將結構體存放到檔案中

來源:互聯網
上載者:User

標籤:

 

 

#include <stdio.h>#include <stdlib.h>#define MAXTLEN 70#define MAXALEN 70#define MAXBKS 10struct 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\n", 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\n",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] != ‘\0‘){                puts("the author:");                gets(library[count].author);                puts("the value:");                scanf("%f",&library[count++].value);                while(getchar() != ‘\n‘){                        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\n",library[index].title,library[index].author,library[index].value);                }                fwrite(&library[filecount],size,count-filecount,pbooks);        }else{                puts("No books? Too bad\n");        }        puts("Bye\n");        fclose(pbooks);        return 0;}

 

Current contents of book.dat: C語言權威指南 by jimmy: $68.00PHP項目大全 by jimmy: $99.90please add the new book, title:

 

C語言:將結構體存放到檔案中

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.