'Hex' and 'decimal' and the like only exist as textual data. A number is a number is a number, no matter how you
write it.
Thus, FF hexadecimal == 255 decimal == 377 octal == 11111111 binary == 2222 trinary == etc. The number is the same. The way it is written is different.
So, if you want to write a single
byte, you must use the
unformatted output operations:
ostream::
put() or
ostream::
write().
So, if you wanted to modify the sixth byte in a file to have the value 0x41 (in ASCII that's a capital 'A'):
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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
void create_file( const string& filename )
{
cout << "Creating '" << filename << "'..." << flush;
ofstream outf( filename.c_str() );
outf << "Have a nice day!\n";
outf << "See you later, handsome!\n";
outf.close();
cout << "\b\b\b \nDone.\n\n";
}
void modify_file( const string& filename )
{
cout << "Modifying '" << filename << "'..." << flush;
fstream f(
filename.c_str(),
ios::in | ios::out | ios::binary
);
f.seekp( 5, ios::beg );
f.put( 0x41 );
f.close();
cout << "\b\b\b \nDone.\n\n";
}
void display_file( const string& filename )
{
string s;
ifstream f( filename.c_str() );
unsigned n = 0;
cout << "Contents of '" << filename << "'\n";
while (getline( f, s ))
cout << ++n << ": " << s << endl;
f.close();
cout << endl << endl;
}
int main()
{
const char* filename = "hello.txt";
create_file ( filename );
display_file( filename );
modify_file ( filename );
display_file( filename );
return 0;
}
|
Some notes:
Line 23 is optional. I opened the file in
binary mode. This wasn't necessary in this case, since the file was a text file. However, when dealing with binary data it is usually a good idea to open files in binary mode.
The unformatted I/O functions take
char as argument... which may be
signed or
unsigned depending on your implementation -- so you should always cast to the appropriate type. It will work correctly either way.
Well, that's all the over-the-top example you're going to get from me... Hope this helps.