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

6
  • seek() casually helps with that. But your case is different. Commented Oct 28, 2020 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?. Commented Oct 28, 2020 at 20:09
  • godbolt.org/z/asq7hq Commented Oct 28, 2020 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. Commented Oct 28, 2020 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. Commented Oct 28, 2020 at 20:19

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

3 Comments

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 ;-)
@πάνταῥεῖ: 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."
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.