简体   繁体   中英

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().

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??? Any help would be appreciated.

Since you have tagged 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) . Because if size of struct would ever be changed and become bigger than your hardcoded size, then you going to get a bug.

  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. 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.
    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.
    • If u use fprintf and fscanf ,data will be stored in human redable format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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