简体   繁体   English

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

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

I am new. 我是新的。 I have some questions, any help would be appreciated. 我有一些问题,任何帮助将不胜感激。 I have a struct and write it to a file using the write(). 我有一个结构,并使用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));

Now I have a file named "output" in hard disk and then I want read the file to test data. 现在,我的硬盘中有一个名为“输出”的文件,然后我想读取该文件以测试数据。

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);

At the moment, I have bufferRead but I dont know how to read buffer to insert data to struct??? 目前,我有bufferRead但我不知道如何读取缓冲区以将数据插入到结构中? Any help would be appreciated. 任何帮助,将不胜感激。

Since you have tagged C++ 由于您已标记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. You'd rather allocate a buffer of size sizeof(PointFull) . 您宁愿分配一个大小为sizeof(PointFull)的缓冲区。 Because if size of struct would ever be changed and become bigger than your hardcoded size, then you going to get a bug. 因为如果struct的大小将被更改并且变得大于您的硬编码大小,那么您将得到一个错误。

  2. Use a local buffer unless you really need to use a dynamic memory. 除非确实需要使用动态内存,否则请使用本地缓冲区。 I assume that in your code you don't really need an allocation. 我认为在您的代码中您实际上不需要分配。 It's just that you may easily forget to deallocate the memory, whereas buffer deleted automagically when a function returns. 只是您可能会轻易忘记分配内存,而在函数返回时会自动删除缓冲区。

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

Also note: your struct might be aligned by inserting a padding. 另请注意:您的结构可能会通过插入填充对齐。 Although I don't think it would be the case with PointFull, anyway, when you need to serialize structures like here, you'd better declare it with #pragma pack to not allow the padding. 尽管我不认为PointFull会是这种情况,但是,当您需要序列化此处的结构时,最好使用#pragma pack声明它以不允许填充。 Eg: 例如:

#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
  • You can use fwrite and fread to write data into file and read from file. 您可以使用fwrite和fread将数据写入文件或从文件读取。
    Below is sample code for same. 以下是相同的示例代码。

      #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; } 
    • If u use fwrite data will be written in binary or ascii format.To read that data u have to use fread. 如果您使用fwrite,则数据将以二进制或ascii格式写入。要读取该数据,您必须使用fread。
    • If u use fprintf and fscanf ,data will be stored in human redable format. 如果您使用fprintf和fscanf,则数据将以可人工复制的格式存储。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM