Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

c++ - This code is meant to output Hello World. but it outputs 0x22fed8

I'm learning File Handling in C++, but there is a problem here. I am trying to read a file. This code is meant to output Hello World. but it outputs 0x22fed8.

#include <iostream>
#include <fstream>

using namespace std;

    int main()
    {
        fstream file;
        file.open("test.txt",ios::in|ios::out);
        file << "Hello World";
        cout << file;
        file.close();

        return 0;
    }

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Simple solution

As others have pointed out, directly printing a file to a stream does't work. Printing the file contents would require opening another stream that reads from the file, or re-setting your stream's read pointer to the beginning and then reading the whole file again (as others have shown).

C++ doesn't do this automatically but you can do it manually (here, opening a new stream):

ifstream ifs("filename");

Now, writing the file contents to another stream is a trivial addition. Instead of writing the file, simply write the file buffer:

cout << ifs.rdbuf() << endl;

That's all! No loop needed to read the file line by line.

Testing for valid streams

While we're on the subject of loops, beware of code that reads files in a loop in the following manner:

while ( !file.eof() )

This code produces an endless loop when there's a reading error. This an happen in many, many situations. Consider e.g. that the file is deleted while you read it, or that someone removes the USB device containing the file or that the file is wrongly formatted. All these cases would create an infinity loop here. Never only test for eof in a stream.

Luckily, the solution to this problem is also quite simple. Furthermore, it explains why your original code yielded such a weird result. In fact, streams in C++ have an implicit conversion to a bool-like type. For reasons explained elsewhere (cue: safe bool idiom), it is actually converted to void*.

This makes it easy to test whether a stream is in a valid, not-at-end state and can safely be read from. Therefore, we can reformulate the loop appropriately:

while (file) …

The above code relies on the conversion to void* taking place. Any nonnull pointer indicates a valid stream. Now, the same happens in your code:

cout << file;

Since there's no appropriate overload for operator << that takes a stream, C++ looks for other overloads and finds an overload for pointers. So it implicitly calls something like this:

cout << static_cast<void*>(file);

Better solution

I've explained a simple, working solution above. However, this solution requires re-opening the file and reading it to memory again. This doubles the work required. We can make this better by introducing a new class that acts like a stream and that actually sends each output to two streams at once. This way, you can write your data both to the file and to the standard stream at the same time. No need to re-read the file.

The class in itself is quite simple. The following complete code demonstrates the general principle:

#include <iostream>
#include <fstream>

struct sinkpair {
    sinkpair(std::ostream& a, std::ostream& b) : a(a), b(b) { }

    // Forward all ouputs to both streams.
    template <typename T>
    sinkpair& operator <<(T const& value) {
        a << value;
        b << value;
        return *this;
    }

    // Explicit overload needed for manipulators such as `endl`.
    sinkpair& operator <<(std::ostream& (*manip)(std::ostream&)) {
        a << manip;
        b << manip;
        return *this;
    }

private:
    std::ostream& a;
    std::ostream& b;
};

int main() {
    std::ofstream ofs("test.txt");
    sinkpair sp(std::cout, ofs);
    sp << "Hello" << std::endl;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...