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