tags:

views:

105

answers:

3

What I am doing is opening my file using fstream at the start of the main and closing it at the end. In between I am writing "Hello World" and after that reading what I wrote but the result is always weired charecters and not the "Hello World". I did do a cast to char but that didnt help. Any way I can do this?

+2  A: 

You need to interpose an fseek call when you switch from reading to writing, or viceversa. (Of course, you also need to fopen for "r+" or the like, so that both reading and writing are allowed, but I imagine you are already aware of that -- the need for seeking in order to switch between reading and writing is a lesser known fact).

As this page puts it,

For the modes where both read and writing (or appending) are allowed (those which include a "+" sign), the stream should be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between either a reading operation followed by a writing operation or a writing operation followed by a reading operation.

Alex Martelli
fseek and fstream? I dont think so. The question is tagged C++ not C, so a C++ answer would be more appropriate.
camh
@camh, in my answer, I quoted extensively from `cplusplus.com`: it's not my fault (nor is it the guys' at `cplusplus.com` of course;-) that C++ incorporates (a version of) C as a subset, and therefore this answer works just fine (while as @Mike's answer observes, doing it with `std::fstream` is _not_ quite as easy). If you think there's a better way to do it (with `std::fstream` and w/o `fopen`), why not just post it?
Alex Martelli
@Alex, If I think there's something wrong with your answer, I will comment on it, as I have done. I do not need to post my own answer to participate. You cannot mix iostreams and stdio, so your answer is at best irrelevant (stdio is not relevant to a question about iostreams), and at worst, wrong. That C++ includes a subset of C does not mean it is a good idea to use that subset in a pure C++ program. Not being exception safe (no auto-closing of fopened files unless you write your own wrappers) is enough for me to discourage use of this C subset in pure C++ code.
camh
+1  A: 

I'd be amused if this works, because I always had to open a file twice to do that: once for reading and once for writing. Even then, I had to write the whole file out and close it (which flushed the OS buffers) before I could be sure I could read the whole file and not get an early EOF.

Nowadays, since I use Unix-style operating systems, I would just use the pipe() function. Not sure if that works in Windows (because so much doesn't, like select() on files).

Mike DeSimone
+1  A: 

Make sure you are seeking to the beginning of the file before reading, like so:

fileFStream.seekg(0, ios_base::beg);

If that doesn't work, post your code.

DominicMcDonnell