I'm trying to read a simple text file returning its content as const char*.
The problem is the type of the function's return. When I return the file's content as std::string
I get no problem and the external string variable will keep the file content all the time, but when I try to return the content as const char*
sometimes the returning variable hold the file content and sometimes don't. The way I'm trying to handle that isn't safe at all. How can I fix it?
static const char* readFile(const char* filePath)
{
std::ifstream file(filePath);
if (file.is_open())
{
std::string line;
std::stringstream ss;
//while(getline(file, line))[...] will result in the same issue.
ss << file.rdbuf();
file.close();
std::string value = ss.str();
return const_cast<char *>(value.c_str());
}
return nullptr;
}
1 - Changing the function signature to std::string all the time I have the file content in my returning string;
2 - Even if the returning variable remaining as const char*
and the string cast is something like: ss.str().c_str();
or &(ss.str())[0];
It cannot guarantee the data will be pass as const char*
.
I know I can still use std::string and convert later the result as char, but I still wonder how can I just convert the file content as const char*
.
Thanks!