- 结构体中的数据类型不统一,此时最适合用二进制的方式进行读写
- 读写单个结构体
#include <stdio.h>
typedef struct{
char *name;
int age;
double height;
} Person;
int main()
{
Person p1 = {"lnj", 35, 1.88};
FILE *fp = fopen("person.stu", "wb+");
fwrite(&p1, sizeof(p1), 1, fp);
rewind(fp);
Person p2;
fread(&p2, sizeof(p2), 1, fp);
printf("name = %s\n", p2.name);
printf("age = %i\n", p2.age);
printf("height = %lf\n", p2.height);
return 0;
}
#include <stdio.h>
typedef struct{
char *name;
int age;
double height;
} Person;
int main()
{
Person ps[] = {
{"zs", 18, 1.65},
{"ls", 21, 1.88},
{"ww", 33, 1.9}
};
FILE *fp = fopen("person.stu", "wb+");
fwrite(&ps, sizeof(ps), 1, fp);
rewind(fp);
Person p;
while(fread(&p, sizeof(p), 1, fp) > 0){
printf("name = %s\n", p.name);
printf("age = %i\n", p.age);
printf("height = %lf\n", p.height);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
typedef struct person{
char *name;
int age;
double height;
struct person* next;
} Person;
Person *createEmpty();
void insertNode(Person *head, char *name, int age, double height);
void printfList(Person *head);
int saveList(Person *head, char *name);
Person *loadList(char *name);
int main()
{
Person *head = loadList("person.list");
printfList(head);
return 0;
}
Person *loadList(char *name){
FILE *fp = fopen(name, "rb+");
if(fp == NULL){
return NULL;
}
Person *head = createEmpty();
Person *node = (Person *)malloc(sizeof(Person));
while(fread(node, sizeof(Person), 1, fp) > 0){
node->next = head->next;
head->next = node;
node = (Person *)malloc(sizeof(Person));
}
free(node);
fclose(fp);
return head;
}
int saveList(Person *head, char *name){
FILE *fp = fopen(name, "wb+");
if(fp == NULL){
return -1;
}
Person *cur = head->next;
while(cur != NULL){
fwrite(cur, sizeof(Person), 1, fp);
cur = cur->next;
}
fclose(fp);
return 0;
}
void printfList(Person *head){
Person *cur = head->next;
while(cur != NULL){
printf("name = %s\n", cur->name);
printf("age = %i\n", cur->age);
printf("height = %lf\n", cur->height);
printf("next = %x\n", cur->next);
printf("-----------\n");
cur = cur->next;
}
}
void insertNode(Person *head, char *name, int age, double height){
Person *node = (Person *)malloc(sizeof(Person));
node->name = name;
node->age = age;
node->height = height;
node->next = head->next;
head->next = node;
}
Person *createEmpty(){
Person *head = NULL;
head = (Person *)malloc(sizeof(Person));
if(head == NULL){
return head;
}
head->next = NULL;
return head;
}