Binary file not saving into same file

I can't seem to get my code to save the buffer into the same binary file. I read the file and placed it into a buffer, and after changing the values of the buffer at a position, I want to overwrite it and place it back into the file.
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
39
40
#include <iostream>
#include <fstream>
using namespace std ;

int main(){
	// Open file as binary
	fstream file;
	file.open( "binaryFile", ios::in|ios::binary);
	if(file.is_open()){
		// Local variables
		int size = 0; 
		char* buffer;
		// Get the length of the file
		file.seekg(0, file.end); 
		size = file.tellg() ; 
		// Go back to the top of the file
		file.seekg(0, file.beg);
		// Create a buffer and read file into buffer
		buffer = new char[size]; 
		file.read( buffer, size );
		// Change value of the hex
		for ( int i = 0; i < size; i++ ){	
			if( buffer[i] == 127){
				buffer[i] = 126;
				printf("%X ", buffer[i]);
			}
		}
		// Write it back to the file	
		file.seekg(0, file.beg);
		for ( int i = 0; i < size; i++ ){	
			file << buffer[i];
		}
		delete [] buffer;
		file.close();
	}
	else{
		cout << "Unable to open file" << endl;
	}
	return 0;
}
Hi,

You opened the file for reading, but not writing?
I thought fstream does both read and write, so making it an fstream i should be able to perform both operations
fstream can be used for input-only or for output-only, or for both input and output.

Input:
 
    file.open( "binaryFile", ios::in | ios::binary);
Output:
 
    file.open( "binaryFile", ios::out | ios::binary);
Both input and output:
 
    file.open( "binaryFile", ios::in | ios::out | ios::binary);

Topic archived. No new replies allowed.