Hey;

I am having problem with the read and write functions in fstream. They need to have a const char * to read or write from/to buffer. I need to work with integers.

Here what happens:

for(int i = 0; i < numberOfValues; i++)
		{
			
			int random = rand() % 100;
			cout << random;
			file.write((char *)&random, sizeof(int));

			int read;
			file.read((char *)&read, sizeof(int));
			cout << read;
		}

This code writes a value and tries to read it back. But the results don't match. What is the problem, and what is the solution of course :)

Try writing your code like this...please note that I write to the file and then close and then open for input.

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

int main()
{
	ofstream		file1("test");

	int random = rand() % 100;
	cout << random << endl;
	file1.write((char *)&random, sizeof(int));

	file1.close();

	ifstream		file2("test");

	int read;
	file2.read((char *)&read, sizeof(int));
	cout << read << endl;

	file2.close();

	return 0;
}

you are using the same fstream object to do both reading and writing. That is ok, but you have to call seekg() between the two in order to reset the file pointer back to the beginning of the int that was written.

[edit]Or use ifstream and ofstream as ^^^ suggested.

Nope, that didn't work for me. I'm getting upset, what the hell is going on in that file !?

Output:
41-858993460
67-858993460
34-858993460
0-858993460
69-858993460
24-858993460
78-858993460
58-858993460
62-858993460
64-858993460
5-858993460
45-858993460
81-858993460
27-858993460
61-858993460
91-858993460
95-858993460
42-858993460
27-858993460
36-858993460

bool CreateRandFile(char* fileName, int numberOfValues)
{
	ofstream fileo(fileName, ios::out | ios::binary );
	ifstream filei(fileName, ios::in | ios::binary);
	if(!fileo.is_open())
	{
		cerr << "Error on creating file: " << fileName;
		return false;
	}

	else if(!filei.is_open())
	{
		cerr << "Error on reading file: " << fileName;
		return false;
	}

	else
	{
		for(int i = 0; i < numberOfValues; i++)
		{
			int random = rand() % 100;
			cout << random;
			fileo.write((char *)&random, sizeof(int));

			int read;
			filei.read((char *)&read, sizeof(int));
			cout << read << endl;	
		}
	}
	return true;
}

I found it. I needed to add "fileo.flush();" just after trying to write down. That was a silly mistake.

Everyone be careful about flushing, lol.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.