Reading Multiple Integers from Binary File

Apr 10, 2020 at 5:12pm
I am really baffled and cannot figure out what the problem here is. I am writing 3 Integers to a file and try to read them later again. But I get some random data. I checked the binary file with an hex editor, and the integers are written just fine.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
int Car::save(const std::string& name){
    std::ofstream writer(name);
    if(!writer.is_open()){
        std::cout << "Filestream Error! Couldn't open file!\n";
        return FAIL;
    }
    writer.write(reinterpret_cast<const char*>(&this->distance), sizeof(int));
    writer.write(reinterpret_cast<const char*>(&this->service_distance), sizeof(int));
    writer.write(reinterpret_cast<const char*>(&this->service_val), sizeof(int));
    writer.close();

    return SUCCESS;
}

// Car::load is static
Car Car::load(const std::string& name){
    std::ifstream reader(name);
    if(!reader.is_open()){
        std::cout << "Filestream Error! Couldn't open file!\n";
        return Fahrzeug();
    }

    Car car = Car();
    int x, y, z;
    std::cout << "Reading\n";
    reader >> x >> y >> z;
    std::cout << "x: " << x <<"\ny: " << y << "\nz: " << z << "\n";
    reader.close();
    return fahrzeug;
}


this is how I call the functions in main
1
2
3
4
...
car.save("car.dat")
Car new_car = Car::load("car.dat");
...


What is wrong with my reading process?
Apr 10, 2020 at 5:14pm
You're writing the the raw data of the ints to file by using write(), but you're reading them in (line 26) as if they were human-readable numbers.

Remove lines 7 to 10, and replace them with
writer << distance << " " << service_distance << " " << service_val;

PS: You don't need to call writer/reader.close() at the end of the scope, it will be done automatically when the scope of the file stream ends.
Last edited on Apr 10, 2020 at 5:16pm
Apr 10, 2020 at 5:21pm
First in your write function you should really be opening the file in binary mode. In your read function you should also be opening the file in binary mode, and use read() (the opposite of write) instead of the extraction operator.

Apr 10, 2020 at 6:34pm
For someone who might come in and have a look what I did to fix this

1
2
3
4
5
6
7
8
9
10
11
...
std::ofstream writer(name, std::ofstream::binary);
...
...
std::ifstream reader(name,std::ifstream::binary);
....
....
reader.read(reinterpret_cast<char*> (&x), sizeof(int));
reader.read(reinterpret_cast<char*> (&y), sizeof(int));
reader.read(reinterpret_cast<char*> (&z), sizeof(int));
...


Thanks to both of you, I preferred the binary solution, since I wanted to get a hang of writing it binary to a file.
Topic archived. No new replies allowed.