A File System Problem

I have a little question as to why this doesn't work. There are no compiler errors and the encode function is for xor. Any ideas?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void encodeFile(string inputFileName,string outputFileName,string key)
{
	fstream fileStreamIn(inputFileName,fstream::ate | fstream::in | fstream::out);
	size_t read_buffer(840000);// this adjusts the read limit

	while(fileStreamIn)
	{
		string readBuffer(840002,'\0');  
		// Reads and gives sizes
		fileStreamIn.read(&readBuffer.front(), read_buffer);
		size_t count = fileStreamIn.gcount();
		readBuffer.resize(count);
		readBuffer = encode(readBuffer,key);
		fileStreamIn.write(readBuffer.c_str(),readBuffer.length()); 		
			if (!count) 
				break;  
		}
		fileStreamIn.close();
}
In what way does it "not work"? What did you expect it to do, what did it actually do?
A few thoughts.

Parameter outputFileName is not used.
The input file opened for output too (why?). Why is the openmode ate used?
There is no check on whether the read() succeeded - the value of count is not checked until after the buffer has been processed.

Assuming the input file should be unchanged, and the encoded version should be written to the output file, this might do. Note the files are opened in binary mode. Text mode can do translation of some characters such as line endings which may not be useful if the file is to be encoded/decoded.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void encodeFile(string inputFileName, string outputFileName,string key)
{
    ifstream fileStreamIn(inputFileName, ios::binary);
    ofstream fileStreamOut(outputFileName, ios::binary);
    
    const size_t buffer_size(840000);
    string readBuffer(buffer_size, 0);
    size_t count;
    
    while (fileStreamIn.read(&readBuffer.front(), buffer_size), count = fileStreamIn.gcount())
    {
        readBuffer.resize(count);
        readBuffer = encode(readBuffer,key);
        fileStreamOut.write(&readBuffer.front(), readBuffer.length());
        readBuffer.resize(buffer_size);   
    }

}


fileStreamIn.read(&readBuffer.front(), read_buffer);

You can't use a string like this because it doesn't guarantee a continuous memory block.
From C++11 a string does use a contiguous block of memory. In earlier versions to be safe one could use a std::vector<char> which would always give a contiguous allocation.

http://www.cplusplus.com/forum/windows/102638/#msg552533

Topic archived. No new replies allowed.