fstream to const char *

蹲街弑〆低调 提交于 2019-12-06 11:58:33

问题


What I want to do is read a file called "test.txt", and then have the contents of the file be a type const char *. How would one do this?


回答1:


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

Be careful not to explicitly call delete on data




回答2:


It's highly unlikely you really want to do that. The contents of the file (which may be either text, or binary data) are unlikely to represent a (valid) pointer to a char on your architecture, so it is not really meaningful to represent it [the content] as a const char *.

What you may instead want is to load the contents of the file in memory, and then store a pointer (of type const char*) to the beginning of the given block. </pedantry> One way of achieving that:

#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)
}



回答3:


You need to:

  1. create a function returning a const char*
  2. open an fstream on the file
  3. seek to its end
  4. determine the file length by looking at the file position (tell)
  5. seek back to the beginning
  6. create a char* to contain the file contents
  7. read the file contents into the char*
  8. return the char* pointer, with the function return adding the const
  9. the file is closed automatically by the fstream going out of scope


来源:https://stackoverflow.com/questions/4010207/fstream-to-const-char

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!