0

Suppose I have a file opened with the C syntax

FILE* fp = fopen("whatever.txt", "w");
// Library function needs FILE* to work on
libray_function(fp);

// Now I'd like to copy the contents of file to std::cout
// How???

fclose(fp);

I would like to be able to copy the contents of that file in a C++ ostream (like a stringstream or maybe even std::cout). How can I do that?

Kerrek SB
  • 428,875
  • 83
  • 813
  • 1,025
Iam
  • 381
  • 1
  • 3
  • 13

3 Answers3

3

You could use an ifstream and rdbuf():

#include <fstream>
#include <sstream>

std::ifstream in("whatever.txt");
std::ostringstream s;
s << in.rdbuf();

or:

std::ifstream in("whatever.txt");
std::cout << in.rdbuf();
hmjd
  • 113,589
  • 17
  • 194
  • 245
  • @PiotrNycz, yes. Is there a reason you think it won't? – hmjd Sep 25 '12 at 15:16
  • I thought it only works for stringstream's where all contents is in streambuf. For filebuf I believe it is not common to have in buffer let say entire 1GB file... But I did not try. Just curious you have any link describing this `os << buf` operator? – PiotrNycz Sep 25 '12 at 15:32
  • @PiotrNycz, you may find this useful: http://sunsite.ualberta.ca/Documentation/Gnu/libstdc++-2.90.8/html/27_io/howto.html – hmjd Sep 25 '12 at 16:01
  • I was wrong - ignore my comment/request. +1 for that was an opportunity to read the right chapter from the standard. – PiotrNycz Sep 25 '12 at 16:05
  • Thanks - I was writing my last comment without seeing your last one. – PiotrNycz Sep 25 '12 at 16:06
1

You've opened the file for write. You're going to need to close it and reopen it anyway, you might as well open it however you please (as an istream if you like). Then it just depends how much you care about performance. If you actually care, you should read it in chunks (at least 512 bytes at a time). If you don't care about performance you can read one byte, spit out one byte.

CrazyCasta
  • 22,698
  • 4
  • 38
  • 66
0

Close it first.

fclose(fp);

Then open again

string line;
ifstream myfile ("whatever.txt");
if (myfile.is_open())
{
    while ( myfile.good() )
    {
        getline (myfile,line);
        cout << line << endl;
    }
    myfile.close();
}
shan
  • 1,084
  • 3
  • 13
  • 27
  • 1
    This is C++ and you certainly almost never need/want to use `is_open`, `good` or `close`, neither did the OP say anything about line-based data. See also [this question](http://stackoverflow.com/q/5605125/743214). – Christian Rau Sep 25 '12 at 13:18
  • Hmm.... thanks. i see. He is not asking line based data... – shan Sep 25 '12 at 13:23