Jeroen
Jeroen

Reputation: 16825

std::string Not Getting Terminated Properly

When I send a std::string to the output stream by calling ostream << string.c_str(); the string is not being terminated correctly. Why is this?

class Application {
public:
    bool print() {
        out << "Content-Type: text/html; charset=utf-8\r\n\r\n";
        std::ifstream inFileStream;
        inFileStream.open("./test.html");
        if(!inFileStream.is_open()) {
            out << "Error Opening File";
            return true;
        }
        boost::uintmax_t templateSize = boost::filesystem::file_size("./test.html");
        std::string output;
        char* templateData = new char[templateSize];
        char* bytePtr = templateData;
        inFileStream.read(templateData, templateSize);

        std::ofstream logFile;
        logFile.open("/tmp/test.log");
        while(*bytePtr != EOF) {
            if(*bytePtr ==  '{')
                readVar(&bytePtr, &output);
            else
                output.push_back(*bytePtr);

            bytePtr++;
        }
        delete[] templateData;
        output.push_back(0);
        logFile << output.c_str();
        return true;

    }
private:
    void readVar(char** bytePtrPtr, std::string* output) {
        while(**bytePtrPtr != EOF) {
            if(**bytePtrPtr == '}')
                return;
            output->push_back('*');
            (*bytePtrPtr)++;
        }
    }
};

The output of this (inside the log file) includes the properly parsed test.html, but also some additional byte garbage.

Upvotes: 0

Views: 90

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153840

The read data isn't terminated by EOF. You dump some junk from the file which sits between the end of the file and the first char which converts to EOF. You should stop your loop adding characters to output once you processed n chars where n is the result of the call to inFileStream.read(...).

Upvotes: 2

Related Questions