文件操作(结构体)

将结构体内容写入到文件中

#include<stdio.h>
#include<string.h>

struct student 
{
    char name[100];
    int age;
};

int main()
{
    struct student st = {"wangqinghe",30};
    FILE * p = fopen("./c.txt","wb");
    fwrite(&st,sizeof(st),1,p);
    fclose(p);
    return 0;
}    

写入到文件中,文件大小是104b,(struct类的大小),多余的未填充的字段会是乱码。

会将整个结构大小和内容写入。

#include<stdio.h>
#include<stdlib.h>

struct student
{
    char name[100];
    int age;
};

int main()
{
    struct student st = {0};
    FILE *p = fopen("./c.txt","rb");
    fread(&st,sizeof(st),1,p);
    fclose(p);
    printf("name = %s, age = %d
",st.name,st.age);
    return 0;
}

运行结果:

exbot@ubuntu:~/wangqinghe/C/20190723$ gcc readWrite.c -o readWrite

exbot@ubuntu:~/wangqinghe/C/20190723$ ./readWrite

name = wangqinghe, age = 30

原文地址:https://www.cnblogs.com/wanghao-boke/p/11240352.html