문제

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?

도움이 되었습니까?

해결책

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();
}

다른 팁

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();

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top