将内容从 C 文件传输到C++流

Transfer contents from C FILE to C++ stream

本文关键字:传输 C++ 文件      更新时间:2023-10-16

>假设我用 C 语法打开了一个文件

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

我希望能够在C++流(如stringstream甚至std::cout)中复制该文件的内容。我该怎么做?

您可以使用

ifstreamrdbuf()

#include <fstream>
#include <sstream>
std::ifstream in("whatever.txt");
std::ostringstream s;
s << in.rdbuf();

或:

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

您已打开文件进行写入。无论如何,您都需要关闭它并重新打开它,您也可以随心所欲地打开它(如果您愿意,可以作为 istream)。然后,这仅取决于您对性能的关心程度。如果你真的关心,你应该分块读取它(一次至少 512 字节)。如果你不关心性能,你可以读取一个字节,吐出一个字节。

先关闭它。

fclose(fp);

然后再次打开

string line;
ifstream myfile ("whatever.txt");
if (myfile.is_open())
{
    while ( myfile.good() )
    {
        getline (myfile,line);
        cout << line << endl;
    }
    myfile.close();
}