fstream到const char*

Q2F*_*b3k 2 c++ fstream

我想要做的是读取一个名为"test.txt"的文件,然后让文件的内容为const char*类型.怎么会这样做?

Arm*_*yan 6

#include <string>
#include <fstream>

int main()
{
   std::string line,text;
   std::ifstream in("test.txt");
   while(std::getline(in, line))
   {
       text += line + "\n";
   }
   const char* data = text.c_str();
}
Run Code Online (Sandbox Code Playgroud)

注意不要显式调用数据删除


eq-*_*eq- 5

您不太可能真的想这样做。文件的内容(可能是文本,也可能是二进制数据)不太可能代表一个(有效的)指向架构上的字符的指针,因此将它 [内容] 表示为const char *.

您可能想要的是将文件的内容加载到内存中,然后将指针(类型为 const char*)存储到给定块的开头。</pedantry> 实现这一目标的一种方法:

#include <sstream>
#include <fstream>
// ...
{
    std::ostringstream sstream;
    std::ifstream fs("test.txt");
    sstream << fs.rdbuf();
    const std::string str(sstream.str());
    const char* ptr = str.c_str();
    // ptr is the pointer we wanted - do note that it's only valid
    // while str is valid (i.e. not after str goes out of scope)
}
Run Code Online (Sandbox Code Playgroud)