C++ character array allocation error

I have a function designed to get a file's contents:

bool getFileContents(std::string loc, std::string &code) {
    std::ifstream file(loc.c_str());

    if(!file.is_open())
        return err("Source file could not be read");

    int length;
    file.seekg(0, std::ios::end);
    length = file.tellg();
    file.seekg(0, std::ios::beg);

    char *buffer = new char[length];
    file.read(buffer, length);
    code = buffer;
    delete[] buffer;

    file.close();

    return true;
}

When I run this function, the file's length is always retrieved accurately. However, if I call the function once with a file, call it again with a nonexistent file, then call it one more time with the original file, the character string 'buffer' is larger than the int 'length'.

Well, that may not be accurate, rather - when the string 'buffer' is copied to the string 'code', 'code' is longer than 'length'. 'code' is, in each instance, instantiated immediately before the call to 'getFileContents', so it's not a matter of a previous value.

This also seems to occur if I retrieve the contents of a file, subsequently add or remove some text from the file, and retrieve the same file's contents again.

I have little experience with character strings, and figure that I'm not using them correctly, but the code I'm using came from an example, and I can't for the life of me find anything wrong with it.

Thanks for any help, Wyatt

Answers


Well, the problem is that code = buffer relies on a NUL (\0) character to know where the buffer ends. You may be getting the NUL character by chance sometimes (esp. when the program has just started), but not always. Hence the intermittent behaviour.

Try replacing code = buffer with code = std::string(buffer, length).


Need Your Help

ostream << istream and testing EOF on an empty file, alternatives for getting characters from istream

c++ file-io get eof

this is my first post on stackoverflow, so if I'm doing it wrong, please let me know. I have my final exam for intro C++ programming on wednesday next week, and I have no way of checking my answer...

Jsoup and specific element under TD

java android href jsoup html-table

I'm developing an app based on Jsoup Parsing. I love this class because it's so useful, but just now I have a problem.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.