A simple solution
As others have pointed out, directly printing a file to a stream does not work. To print the contents of a file, you need to open another stream that reads from the file, or reset the read pointer of the stream to the beginning, and then read the entire file again (as others have shown).
C ++ does not do this automatically, but you can do it manually (here, by opening a new thread):
ifstream ifs("filename");
Now writing the contents of the file to another stream is a trivial addition. Instead of writing a file, just write a file buffer:
cout << ifs.rdbuf() << endl;
It's all! No loop is required to read the file line by line.
Valid Thread Testing
While we're in the loop course, beware of code that reads files in a loop like this:
while ( !file.eof() )
This code creates an endless loop when there is a read error. This happens in many, many situations. Consider, for example, that a file is deleted while it is being read, or that someone is deleting a USB device containing the file, or that the file is mistakenly formatted. All of these cases would create a cycle of infinity. Never check only eof in a stream.
Fortunately, the solution to this problem is also quite simple. Also, this explains why your source code gave such a weird result. In fact, threads in C ++ have an implicit conversion to type bool . For reasons explained elsewhere (cue: secure bool identification ), it actually converts to void* .
This makes it easy to check if the stream is in an acceptable state, not at the end, and can be read safely. Therefore, we can reformulate the cycle accordingly:
while (file) âĻ
The above code is based on conversion to void* . Any non- null pointer indicates a valid stream. Now the same thing happens in your code:
cout << file;
Since there is no corresponding overload for operator << that takes a stream, C ++ looks for other overloads and finds overload for pointers. Therefore, it implicitly calls something like this:
cout << static_cast<void*>(file);
The best decision
I explained the simple, working solution above. However, this solution requires reopening the file and reading it into memory again. This doubles the required work. We can do this better by introducing a new class that acts like a thread and actually sends each output to two threads at the same time. Thus, you can simultaneously write your data both to a file and to a standard stream. No need to re-read the file.
The class itself is pretty simple. The following complete code demonstrates a general principle:
#include <iostream>