#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
int main(){
// write file
string file_name = "random_fstream.dat";
ofstream file(file_name, ios_base::out | ios_base::binary);
if (!file) {return EXIT_FAILURE;}
int r = 2;
int c = 3;
file.write(reinterpret_cast<char*>(&r),sizeof(r));
file.write(reinterpret_cast<char*>(&c),sizeof(c));
//------------------------------------------------
// read file
ifstream in(file_name, ios_base::in | ios_base::binary);
if (!in) {return EXIT_FAILURE;}
int x = 0;
int y = 0;
in.read(reinterpret_cast<char*>(&x),sizeof(y));
in.read(reinterpret_cast<char*>(&x),sizeof(y));
cout << x << y << endl;
return 0;
}
I was trying to practice write and read file in C++. First step was to write int value 2 and 3 into the file with binary form. Second step was to read the two number from that file.
Then I got x and y valued both equal to 0, but I expected to receive x=2 and y=3. Where did I do wrong?
Aucun commentaire:
Enregistrer un commentaire