Saving a long int to file?

Hello everyone,
This is a pretty basic question, but I've been having no luck whatsoever in getting this to work.

Basically, I need to output long integers to a file - i.e. the 4 byte values, no formatting as text - as well as strings and other information. I know it's a basic question, but I honestly can find a way to to this. I'm trying to use 'ofstream', but if there's another class I should use please let me know.


Things I've tried:

outfile << myint;
This converts the value into a string rather than just writing the four byte value because the << formats it as text.


1
2
3
4
5
6
char myint2[4];
for(int i = 0; i < 4; i++)
{
	myint2[i] = (char)(myint2 >> (3-i));
}
OutFile.write(myint2,4);

This outputs a strange value to the file. Not sure why.


Help please!
What do you mean by "writing the four byte value"? Do you mean something like:

100 254 66 29?

If so, your second way should work fine, except instead of using .write() just print the chars out as ints like so:

outfile<<static_cast<int>(myint2[0])<</*...*/;
My guess is that he wants to open the file in binary mode.

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
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ofstream fout;
    ifstream fin;

    int my_int=1234;

    fout.open("data.dat",ios::binary);
    fout.write((char*)&my_int,sizeof(int));

    fout.close();

    int my_int2;

    fin.open("data.dat",ios::binary);
    fin.read((char*)&my_int2,sizeof(int));

    fin.close();

    cout << my_int2 << endl;
    cout << "hit enter to quit..." << endl;
    cin.get();

    return 0;
}

Also, take a look at this -> http://cplusplus.com/doc/tutorial/files/ (scroll down)
You can to it like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <fstream>

int main()
{
	std::ofstream ofs("output.txt");

	int myint = 3;

	ofs.write(reinterpret_cast<char*>(&myint), sizeof(myint));

	return 0;
}


That takes into account different sized integers.
Thanks everyone for the response. I don't think I paid enough attention to the tutorial when discussed casting. I'm going with reinterpret_cast<char*>(&myint), and it works.
You should open it in binary. reinterpret_cast are evil if you're not sure what you are doing.
Topic archived. No new replies allowed.