1

I'm trying to use same fstream object for first write the file and after that read the file. when I'm using below code then the codes of writing the file is working but I'm getting junk output instead of texts which written in the file.

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main() {
    fstream file;
    file.open("test.txt",ios::in|ios::out| ios::trunc);

    if (!file) {
        cout << "Error";
    }
    else {
        cout << "success";
        file <<"\n\n1st Line\n 2nd line \n 3rd line\n";
        string filecontent;
        while (file.good()) {
            getline(file, filecontent);
            cout << filecontent << endl;
        }
    }
    return 0;
}

Output

  • `seek()` casually helps with that. But your case is different. – πάντα ῥεῖ Oct 28 '20 at 20:07
  • 1
    `while (file.good())` ensures that the loop is only entered if the stream is good. But `getline(file, filecontent)` can still fail after the test and the result will still be used. Use `while (getline(file, filecontent))` instead. It reads, tests that the read succeeded, and then enters the loop. This is almost the same problem as [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons). – user4581301 Oct 28 '20 at 20:09
  • https://godbolt.org/z/asq7hq – JulianW Oct 28 '20 at 20:09
  • _@Rizni_ Don't post text as images please, this makes many screen readers stall and excludes blind people from participating here, amongst other reasons. – πάντα ῥεῖ Oct 28 '20 at 20:12
  • 1
    This is not really a duplicate. While its use of `while (file.good()()` is a problem, fixing that problem is *not* sufficient to make the code work. – Jerry Coffin Oct 28 '20 at 20:19
  • You need to seek to the start of the stream before reading, I think. – Paul Sanders Oct 28 '20 at 20:23

1 Answers1

4

This code has two separate problems. The first (which others have already pointed out to at least some degree) is that your loop isn't detecting the end of the file correctly. In fact, almost any time you use while (!file.eof()) or while (file.good()), it's going to be a mistake--it won't detect end of file at the right time, so (for example) when you reach the end of the file, you won't detect it at the right time, and you'll see the last item in the file appear to be read twice before the loop exits.

In addition to that, however, you have a problem in that you're writing to the file, then immediately trying to read. That's simply not allowed--you want to do a seek any time you switch between reading and writing.

In this case, you have a bit of a further problem. Since you've just written data into the file, your file's current position is at the end of the file. So even if you could just start reading without seeking, you'd start reading from the end of the file. That, of course, would immediately fail.

So you also really need to seek back to the beginning of the file to be able to read it back in.

So, the big changes here are adding a line like: file.seekg(0); after you finish writing, but before you start to try to read that data back in, and then changing your reading loop to something like:

    while (getline(file, filecontent)) {
        cout << filecontent << endl;
    }

One last point: although it's not going to make a big difference in this case, I'd advise using "\n" instead of std::endl. std::endl writes a new-line and flushes the file buffer. When you're writing to the screen it won't make any real difference, but when writing to a normal file flushing the buffer unnecessarily can and will slow your code substantially (10x slower is pretty common).

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • The good thing with falsely hammered duplicates is, that it raises some people at the plan, who are expericenced enough to correct their error, and giving a detailed answer what's really needed to fix, and be useful for future research. A _poor excuse_ I know ;-) – πάντα ῥεῖ Oct 28 '20 at 20:45
  • @πάνταῥεῖ: Oh, I'm not bothered by a mistake. I only commented on it to assure it didn't get closed again while I was writing an answer. Frustrating as hell when you spend time typing an answer (especially when you're a lousy typist like I am), click "post" only to receive: "This post is no longer accepting answers." – Jerry Coffin Oct 28 '20 at 20:55
  • 1
    I can feel with you, won't be the 1st time I find myself in that same situation. Lousy typist also, and to worsen, not a native speaker either. – πάντα ῥεῖ Oct 28 '20 at 21:02