How to read and write int to binary files in C++

1 Answer

0 votes
#include <iostream>
#include <fstream>

using namespace std;

int main ()
{
    const char *FILENAME = "data.bin";
    int n = 98631;
    ofstream o(FILENAME, ios::binary);

    o.write((char*)&n, sizeof(n));
    o.close();

    int tmp = 0;
    ifstream i(FILENAME, ios::binary);
    i.read((char*)&tmp, sizeof(tmp));
    i.close();
    
    cout << tmp;

    return 0;
}


/*
run:

98631

*/

 



answered Feb 14, 2020 by avibootz
edited Feb 14, 2020 by avibootz

Related questions

1 answer 187 views
2 answers 254 views
1 answer 166 views
1 answer 218 views
1 answer 235 views
...