-1

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!

Ito
  • 2,167
  • 3
  • 23
  • 32
  • 2
    This is undefined behavior, since you're basically guaranteeing "use-after-free". A `std::string` stores its contents in an allocated buffer, which it returns a `const` pointer to with the `c_str()` and `data()` methods (guaranteed in C++11 and above). The `std::string` destructor frees this allocated buffer, Modifying the string, such as calling the deallocator, makes using that buffer undefined behavior, as the memory has likely been freed. You either need to copy the contents to a new buffer, or return the actual `std::string`. – Alex Huszagh Mar 23 '18 at 05:01
  • 1
    Possible duplicate of [What is std::string::c\_str() lifetime?](https://stackoverflow.com/questions/6456359/what-is-stdstringc-str-lifetime) –  Mar 23 '18 at 05:05
  • *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,* -- So the question is why are you trying to find a problem with your initial solution of using `std::string`? It worked, that should have been good enough -- there was no need to use `char *`. There's an old joke: "Doctor, it hurts when I do this thing with my hand" -- Doctor says, "well don't do that thing to your hand!" – PaulMcKenzie Mar 23 '18 at 05:21

1 Answers1

0

Return a std::string. Problem solved.

Sid S
  • 6,037
  • 2
  • 18
  • 24
  • this answer reminds of comments I sometimes come across in code `i = i + 1 // increments i` you should state why also. – AndersK Mar 23 '18 at 05:48