5

I have a file that I am trying to print to the screen, but all it returns is "0x28fe88", when the file itself is 13 columns by a couple hundred rows.

#include <iostream>
#include <fstream>
#include <istream>
#include <ostream>
#include <cstdlib>
using namespace std;

int main()
{
    //Opens .txt file
    ifstream infile1;
    infile1.open("Taylor.txt");

    //Fail check
    if(infile1.fail())
    {
        cout << "File failed to open.\n";
        exit(1);
    }

    //Prints file to screen (not correctly)
    cout << infile1;

    //Closes file
    infile1.close();
    return 0;
}

I would otherwise not post the full code, but I hope it is short enough to not warrant catching flak.

Son-Huy Pham
  • 1,899
  • 18
  • 19
Tilt-Shifted
  • 61
  • 1
  • 4
  • You're not printing the contents of the file you're printing the ifstream object. – Jesus Ramos Aug 13 '13 at 20:32
  • 2
    `cout << infile1;` *does not* print the file contents to stdout. It's printing the object address out. – greatwolf Aug 13 '13 at 20:32
  • The original code inserts a stream object into a stream. That works because, prior to C++11, stream classes (technically, the base class `basic_ios`), has a conversion to `void*` that indicates whether the stream is in a good state (returns a null pointer if it's not, and a non-null pointer otherwise); what the original code display is the result of this conversion operator. In C++11 that conversion is no longer present; it's been replaced with `explicit operator bool()`, which serves the same purpose without introducing mysterious conversions in non-boolean contexts. – Pete Becker Aug 13 '13 at 20:49

1 Answers1

10

To just print out text file use this cout << infile1.rdbuf();, because now you're printing a pointer to a file.

EDIT: If this didn't work for you, the closest thing to it would be to read file character by character. There are other ways around it using strings, but this code will do just fine:

while(infile1.good()) 
    cout << (char)infile1.get();

It reads character code while the file is good to read and instantly converts it to char (might need some modifications for UNICODE) and prints it out.

FrogTheFrog
  • 1,548
  • 19
  • 32
  • This should also print a pointer, this time the pointer to infile1's buffer object. Try this code: cout.rdbuf(infile1.rdbuf()); – Michael Aug 13 '13 at 20:46
  • `cout << infile1.rdbuf()` works just fine, because who knows :) – FrogTheFrog Aug 13 '13 at 20:51
  • I supplemented this for what I had, but it is still printing the previously stated output. To reiterate, I just want to print the file as is. – Tilt-Shifted Aug 14 '13 at 05:17