Search code examples
c++arraysstructfwritefread

I can't seem to figure out why my read/write to a file functions are not working


I've been doing my project and the last thing I need to do is to save to and start reading a structure array from a file on startup of the program, but I can't figure out why the code isn't loading the information of the file. I know that it does save something since I can open the .dat file and read it in a text editor. I apologize for the terrible style, but I'm still new. That's a sample of just that function in the code:

#include <iostream>
#include <string>
#include<fstream>

using namespace std;

struct property {
    int num;
    char nBrok[50];
    char type[10];
    string adress;
    char outlook[20];
    double price;
    double size;
    int nRooms;
    int floor;
    int status;
};
fstream fp;

void fileWrite(property bDanni[], int n) {
    fp.open("dbase.dat", ios::binary | ios::out);
    if (!fp) {
        cout << "\n Error in file \n"; exit(1);
    }
    fp.write((char*)bDanni, sizeof(property) *n);
    fp.close();
}

int fileRead(property bDanni[]) {
    long pos; int n = 0, i; property b;
    fp.open("dbase.dat", ios::binary | ios::in);
    if (!fp) {
        cout << "\n file does not exist\n"; return n;
    }
    fp.seekg(0l, ios::end);
    pos = fp.tellg();
    fp.close();
    n = pos / (sizeof(property));
    fp.open("dbase.dat", ios::binary | ios::in);
    if (!fp) {
        cout << "\n Error in file \n"; exit(1);
    }
    for (i = 0; i < n; i++) {
        fp.read((char*)&b, sizeof(property));
        bDanni[i] = b;
    }
    fp.close();
    return n;
}
int main() {
    property bDanni[100];
    char answer;
    int total = 0;
    cout << "Do you wat to read from the save file?(y/n): ";
    cin >> answer;
    if (answer == 'y') {
      int total = fileRead(bDanni);
    }
}

Solution

  • The problem is that a C++ std::string is much more complex than a char array. The implementation is not mandated by the standard, but in common implementation, the string element contains a pointer to a character array. That means that your code only stores into the file a pointer value instead of a character string.

    In C++ idiom, the std::string type is said not to be trivially copyable. And the fread-fwrite method can only be used with trivially copyable types.

    That means that you will have to use serialization to replace the raw byte representation of a std::string with a sequence of bytes that represent the useful content of the object, something that you will be able to use at read time to construct back the object. Not really complex but beyond a mere fwrite.