As far as I know fstream is actually intended for read + write combos. The following code works and I believe is standard compliant. It should output "b\nc\nd\n". The only thing I am not sure is whether you have to seek before reading or writing for the first time. I mean, I believe that you are supposed to seekp before you write and seekg before you read, when you switch from reading to writing, but I am not sure if you have to do either at the very beginning. Someone can confirm?
#include <iostream>
#include <fstream>
usingnamespace std;
int main()
{
char c;
//Write some consecutive alphabetic characters to a file
{
ofstream file("test.txt", ios::out | ios::binary);
for (c = 'a'; c <= 'c'; ++c)
{
file.write(&c, 1);
}
}
//Read every character from a file, increment it and write it back
{
fstream file("test.txt", ios::in | ios::out | ios::binary);
long pos = 0;
while (file.read(&c, 1))
{
++c;
file.seekp(pos);
file.write(&c, 1);
++pos;
file.seekg(pos);
}
}
//Read every character from a file and output it on a separate line
{
ifstream file("test.txt", ios::in | ios::binary);
while (file.read(&c, 1))
{
cout << c << endl;
}
}
}