如何在 C++ 中将结构写入文件并读取文件?

How to write a struct to file in C++ and read the file?

我是新来的。我有一些问题,任何帮助将不胜感激。 我有一个结构并使用 write().

将其写入文件
struct PointFull {
    double lat;
    double lon;
};

PointFull item;
void* buffer = malloc(sizeof (item));
int fd = open("output", O_WRONLY | O_CREAT, S_IWUSR | S_IRUSR);
if (fd < 0) {
    printf("Error opening file\n");
    return 1;
}
memcpy(buffer, &item, sizeof (item));
write(fd2, buffer, sizeof (item));

现在我的硬盘里有一个名为"output"的文件,然后我想读取这个文件来测试数据。

int fd2 = open("output", O_RDONLY, S_IWUSR | S_IRUSR);
if (fd2 < 0) {
    printf("Error opening file\n");
    return 1;
}
void* bufferRead;
bufferRead = malloc(100);
read(fd2, bufferRead,100);

目前,我有 bufferRead 但我不知道如何读取缓冲区以将数据插入结构???任何帮助将不胜感激。

因为你标记了 C++

#include <iostream>
#include <fstream>
using namespace std;

struct PointFull {
    double lat;
    double lon;

    PointFull(double lat_in = 0, double lon_in = 0) 
        : lat(lat_in), lon(lon_in) {}
};

int main() {
    PointFull item(123123, 123123);

    cout << "Writing to disk" << endl;
    ofstream fout("saved_point.txt");
    fout << item.lat << ' ' << item.lon;
    fout.close();

    cout << "Reading from disk" << endl;
    PointFull item_from_disk;
    ifstream fin("saved_point.txt");
    fin >> item_from_disk.lat >> item_from_disk.lon;
    fin.close();

    cout << "From RAM and then disk" << endl;
    cout << item.lat << ' ' << item.lon << endl;
    cout << item_from_disk.lat << ' ' << item_from_disk.lon << endl;


    return 0;
}
  1. 您宁愿分配大小为 sizeof(PointFull) 的缓冲区。因为如果结构的大小会发生变化并变得比硬编码的大小更大,那么您就会遇到错误。

  2. 除非确实需要使用动态内存,否则请使用本地缓冲区。我假设在您的代码中您真的不需要分配。只是您可能很容易忘记释放内存,而缓冲区会在函数 returns.

  3. 时自动删除

int fd2 = open("output", O_RDONLY, S_IWUSR | S_IRUSR);
if (fd2 < 0) {
    printf("Error opening file\n");
    return 1;
}
char bufferRead[sizeof(PointFull)];
read(fd2, bufferRead, sizeof(bufferRead));
//Now as you've read it, just cast the memory to struct, and assign it
item = *reinterpret_cast<PointFull*>(bufferRead);
//okay, now item holds the file content, you no longer need the buffer

另请注意:您的结构可能会通过插入填充来对齐。虽然我不认为 PointFull 会是这种情况,但是无论如何,当你需要像这里这样序列化结构时,你最好用 #pragma pack 声明它以不允许填充。例如:

#pragma pack(push, 1) // exact fit - no padding
struct PointFull {
    double lat;
    double lon;
};
#pragma pack(pop) //back to whatever the previous packing mode was
  • 您可以使用 fwrite 和 fread 将数据写入文件和从文件读取数据。
    下面是相同的示例代码。

     #include <stdio.h>
    
     struct PointFull
     {
        int number;
        char text[10];
        double real_number;
     };
    
     int main()
    {
     struct PointFull  data = {1, "Hello!", 3.14159}, read_data;
     FILE *fout = fopen("file_path", "w");
     fwrite(&data, sizeof(PointFull ), 1, fout);
     //   fprintf(fout, "%d %s %f",data.number, data.text, data.real_number);
     fclose(fout);
    
     FILE* fin = fopen("file_path", "r");
     fread(&read_data, sizeof(PointFull ), 1, fin);
     printf("%d %s %lf\n", read_data.number, read_data.text, read_data.real_number);
     fclose(fin);
     return 0;
    }
    
    • 如果您使用 fwrite 数据将以二进制或 ascii 格式写入 format.To 读取该数据您必须使用 fread。
    • 如果您使用 fprintf 和 fscanf,数据将以人类可读格式存储。