Read & write in a file at the same time

Write your question here.
Hello to everibody...7
My problem is to read and write, at the same time, a text file stream.
I have heard about the class file fstream; but it seems does not work
Could you show us your code, and tell us more about what you did and what doesn't work?
It is possible to read and write the same file at different times, and it is possible to read one file and write another at the same time, but it isn't possible to read and write the same file at the same time. Which did you mean?

fstream works fine, but most of the time you access it using ifstream and ofstream objects. Using fstream directly, you can open a file with both in and out flags, but you can only read or write at any one time, as I already said. You can alternate reads and writes very, very quickly, though.


I think you want (decide how to open it flag from list below)

fstream f;

f.open(filename, std::fstream::in | std::fstream::out | std::fstream::{one of app ate trunc} )

and then you can just use >> and << to write to it, and seekp to go to a specific location for next read or write, I think. You should be able to google a ton of examples.

this may be a case where it is easier to open the file as-if binary; I find hopping around easier in that mode.

another, and possibly better approach for *small* files, is to read the whole thing into memory, edit only the memory buffer, and write it out once in a while (say every X seconds and on program exit).

Last edited on
Hello...
I just rememember that it is possibile to read and write streams, at same time, in C language; so I really wonder that this feature is not implemented in C++.
It means I should take into consideration it and adeguate myself to it.
Thank you very much
a stream and a file are not the same thing.
your hard disk is incapable of reading and writing the same location at the same exact moment. Nano seconds apart, sure, but the exact same moment, no. A stream, which may represent a disk file (or something else like a flow on a socket or port), is an abstraction.
Topic archived. No new replies allowed.