-2

I have been trying to print the contents of a file, however, it will not print anything it will only return 0. I have checked and double checked my code and I can't find any reason as to why it won't work. Here is a sample of my code.

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

int main() {
    ifstream infile("test.txt");
    string line;
    if(infile.is_open())
    {
      cout << infile.rdbuf();
    }
    else
    {
      cout << "error" << endl;
    }
    infile.close();
    return 0;
}
  • You never triggered to read anything into the buffer? – πάντα ῥεῖ Feb 21 '17 at 19:54
  • I have the file in the same folder as my main.cpp. I am using xcode on my macbook. – science1324 Feb 21 '17 at 20:02
  • Possible duplicate of [Read whole ASCII file into C++ std::string](http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring) – user4581301 Feb 21 '17 at 20:55
  • @πάνταῥεῖ Actually, why *doesn't* the original code work? `std::cout` is a `std::ostream`, and `std::ostream::operator< – Kyle Strand Feb 21 '17 at 21:32
  • I've deleted my answer. Using `cout << infile.rdbuf()` *should* read the file. Here's a working example on Coliru (printing the source file since I'm not sure there's anything else available to read): http://coliru.stacked-crooked.com/a/ea7ec2dc80016335 – Kyle Strand Feb 27 '17 at 03:35

1 Answers1

0

You can just read it into a string then print it.

#include <string>
#include <fstream>
#include <streambuf>

void func()
{
  // Read into a buffer.
  std::ifstream t("file.txt");
  std::string str;

  t.seekg(0, std::ios::end);   
  str.reserve(t.tellg());
  t.seekg(0, std::ios::beg);

  // Assign to a string.
  str.assign((std::istreambuf_iterator<char>(t)),
            std::istreambuf_iterator<char>());

  // Print out the string to the console.
  std::cout << str << "\n";
}
DiB
  • 454
  • 3
  • 15