Small example of a single-chain table (3) reading and saving a linked list

Source: Internet
Author: User

tag: blog Io OS AR for div C log R

#include <stdio.h> #include <malloc.h> #include <string.h> struct address { int a; int b; char c; struct address *next; }; void SaveToFile(struct address *p, FILE *fp) { if(p != NULL) { do { fwrite(p, sizeof(struct address), 1, fp); p = p->next; } while(p != NULL); } } int load(FILE *fp, struct address **head){int n=0; struct address *p1,*p2; *head = (struct address *) malloc(sizeof(struct address)); memset(*head, 0, sizeof(struct address)); if( fread(*head, sizeof(struct address), 1, fp) != 1) { free(*head); *head = NULL; return(0); } p2 = *head; n++; while( !feof(fp)) { p1 = (struct address *) malloc(sizeof(struct address)); fread(p1, sizeof(struct address), 1, fp); p2->next = p1; p2 = p1; n++; } p2->next = NULL; return(n); } void main() { struct address *head; struct address *Test[10] = {0}; int i = 0; FILE *fp = NULL; for(i=0; i < 10; i++) { Test[i] = (struct address *)malloc(sizeof(struct address)); if(Test[i] != NULL) { memset(Test[i], 0, sizeof(struct address)); Test[i]->a = 65 + i; Test[i]->b = 65 + i; } } for(i = 0; i < 10; i++) { if(i < 10) { Test[i]->next = Test[i+1];} } if((fp = fopen("addrbook.txt", "wb")) != NULL) { SaveToFile(Test[0], fp); fclose(fp); } if((fp = fopen("addrbook.txt", "rb")) != NULL) { load(fp, &head); } }

  

单链表的小例子(三)链表读取和保存

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.