Reading/Writing to file issue

Hi,

I have an IO Class for handling reading from and writing to files and it looks like this:

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
30
31
32
33
34
35
36
37
38
// MANIPULATORS
void IOHandler::setInputSource(string inputSRC)
{
	if(mInputStream.is_open())
		mInputStream.close();
	mInputSRC = inputSRC;
	mInputStream.open(inputSRC.c_str(),);
}
void IOHandler::setOutputSource(string outputSRC)
{
	if(mOutputStream.is_open())
		mOutputStream.close();
	mOutputSRC = outputSRC;
	mOutputStream.open(mOutputSRC.c_str());
}
string IOHandler::readInputFile(void)
{
	string fileContent;
	stringstream buffer;
	buffer << mInputStream.rdbuf();
	fileContent = buffer.str();

	return fileContent;
}
void IOHandler::writeOutputFile(string content)
{
	mOutputStream << content;
}

// ACCESSORS
string IOHandler::getInputSource(void) const
{
	return mInputSRC;
}
string IOHandler::getOutputSource(void) const
{
	return mOutputSRC;
}


The problem is that when I use readInputFile the text gets read into the program correctly, but the content is erased from the file. Is there a way to read it while keeping the file intact?

For reference, the mInputStream variable is an ifstream and mOutputStream is an ofstream.

Thanks
Robin
Last edited on
Bump!
> mInputStream variable is an ifstream
> the text gets read into the program correctly, but the content is erased from the file
If you mean the `physical' file, then it can't happen. You don't have writing permission.
If you mean that you can't do readInputFile() several times, I suppose that the get pointer went to the end of the file.
Reading should not change the file. Are you sure that is what happens?

When opening a file with ofstream it will remove the old content of the file. Maybe this is what happens. If you want to keep the old content you should pass the ate or the app flag when you open the file for writing.
mOutputStream.open(mOutputSRC.c_str(), std::ios::ate);
That is exactly what is happening actually. The actual content of the 'physical' file gets erased. I only use the following lines of code:

1
2
m_IOHandler.setInputSource("data.txt");
string fileContent = m_IOHandler.readInputFile();


This results in that all the text in the file gets stored in fileContent and also everything is erased from the 'physical' file.
mInputStream.open(inputSRC.c_str(),);
This should not even compile, what is being passed to the second parameter?
just a typo when I posted, there is just one parameter.
Topic archived. No new replies allowed.