How to save structure data to a file in the C language?

In C language, file operation functions can be used to write structure data to a file. Here is an example code:

#include <stdio.h>

// 定义一个结构体
struct Person {
    char name[50];
    int age;
    float height;
};

int main() {
    // 创建一个结构体变量,并初始化其中的数据
    struct Person person = {"Alice", 25, 1.75};

    // 打开一个文件,如果文件不存在则创建新文件,写入模式为二进制写入
    FILE *file = fopen("person_data.dat", "wb");

    // 将结构体数据写入文件
    fwrite(&person, sizeof(struct Person), 1, file);

    // 关闭文件
    fclose(file);

    return 0;
}

In the code above, a structure named Person is first defined, then a structure variable person is created and initialized with data in the main function. Next, the fopen function is used to open a file (in this case person_data.dat) and specify the write mode as binary. Then the fwrite function is used to write the data of the structure variable person into the file, where &person represents the address of the structure variable person, sizeof(struct Person) represents the size of the structure, 1 indicates writing one set of structure data, and file represents the file pointer. Finally, the fclose function is used to close the file.

This way, the structure data can be written to the file.

bannerAds