Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading and writing int to a binary file in C++

I am unclear about how reading long integers work. If I say

long int a[1]={666666}
ofstream o("ex",ios::binary);
o.write((char*)a,sizeof(a));

to store values to a file and want to read them back as it is

long int stor[1];
ifstream i("ex",ios::binary);
i.read((char*)stor,sizeof(stor));

how will I be able to display the same number as stored using the information stored in multiple bytes of character array?

like image 935
user2097891 Avatar asked Feb 22 '13 06:02

user2097891


People also ask

How do you write an int in binary?

To convert integer to binary, start with the integer in question and divide it by 2 keeping notice of the quotient and the remainder. Continue dividing the quotient by 2 until you get a quotient of zero. Then just write out the remainders in the reverse order.


1 Answers

o.write does not write character, it writes bytes (if flagged with ios::binary). The char-pointer is used because a char has length 1 Byte.

o.write((char*)a,sizeof(a)); 

(char*) a is the adress of what o.write should write. Then it writes sizeof(a) bytes to a file. There are no characters stored, just bytes.

If you open the file in a Hex-Editor you would see something like this if a is int i = 10: 0A 00 00 00 (4 Byte, on x64).

Reading is analogue.

Here is a working example:

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

using namespace std;


int main (int argc, char* argv[]){
    const char* FILENAM = "a.txt";
    int toStore = 10;
    ofstream o(FILENAM,ios::binary);

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

    int toRestore=0;
    ifstream i(FILENAM,ios::binary);
    i.read((char*)&toRestore,sizeof(toRestore));

    cout << toRestore << endl;


    return 0;
}
like image 144
El Hocko Avatar answered Oct 16 '22 03:10

El Hocko