Fstream and simultaneous I/O

It is possible create a stream (fstream) to read data and then write other information without close the stream?

I use fstream("miFile",ios::bynary) (or fstream("myFile", ios::in | ios::out | ios::binary) )

After reading the information from the file, I try to write with write() method but it always fails...
dun think that is possible without threading. try reading it, store it, edit the data, then open stream and write again?
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?

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
#include <iostream>
#include <fstream>

using namespace 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;
        }
    }
}
Topic archived. No new replies allowed.