c++ reads the entire structure from the file

Goal: Just read once from a file to complete the assignment of the entire structure. Instead of extracting one piece of data each time, assigning it to a certain element of the structure, and then looping, which seems cumbersome.

Principle: Both the structure and the structure array are the contents of consecutive addresses in the memory, but there will be padding in the middle to achieve the alignment effect. But if we write the data to the file together with the padding, this is equivalent to copying a copy of the address space into the file, and then copying it back when reading, doesn't it complete the reading of the entire structure? In this way, there is no need to consider issues such as parsing file content in conventional methods.

#include <iostream>
#include <fstream>
#include <stdio.h>
#include <Windows.h>
using namespace std;
struct MyStruct
{
    int id;
    char name[20];
    float score;
};
int main()
{
    MyStruct myList[3];
    myList[0].id = 1;
    strcpy_s(myList[0].name, "zhang");
    myList[0].score = 60.0;
    myList[1].id = 2;
    strcpy_s(myList[1].name, "wang");
    myList[1].score = 70.0;
    fstream myFile("test.txt", ios::out | ios::binary);
    myFile.write((char*)myList, sizeof(MyStruct) * 3);//将结构体数组整体写入
    myFile.close();
    fstream myFileReader("test.txt", ios::binary | ios::in);
    memset(myList, '\0', sizeof(MyStruct) * 3);
    myFileReader.read((char*)myList, sizeof(MyStruct) * 3);
    for (int i=0;i < 3;i++) {
        printf("id:%d\n", myList[i].id);
        printf("name:%s\n", myList[i].name);
        printf("score:%f\n", myList[i].score);
    }
}

Use the write function to write the entire file from the memory to the file, and use the read function to read the entire file from the memory to the memory.

operation result:

As you can see, there is no problem reading data from the file.

 In the code, I only assigned values ​​to the first two in the structure array, so the last one has no data. But there is also a problem here. I clearly used memset(myList, '\0', sizeof(MyStruct) * 3); to assign all values ​​​​to this memory area to 0. How could it be garbled? (It feels like hot, hot, hot corresponds to emptiness, which is weird)

Note: To modify the file content, you must use the write() method instead of directly opening the file to modify it, otherwise the code will be garbled, as shown below.

 

Thinking about the reason, I guess it is because the data stream is not transmitted in the form of bytes, but binary. Modification at the bytecode level will cause the format to be unable to be aligned.

Guess you like

Origin blog.csdn.net/qq_16198739/article/details/127185502