0

当我std::string通过调用字符串将 a 发送到输出流时,ostream << string.c_str();该字符串未正确终止。为什么是这样?

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)++;
        }
    }
};

这个(在日志文件中)的输出包括正确解析的test.html,但也包括一些额外的字节垃圾。

4

1 回答 1

2

读取的数据不以EOF. 您从位于文件末尾和char转换为EOF. output处理完字符后n,您应该停止循环添加字符,n调用的结果是inFileStream.read(...).

于 2013-10-01T20:20:42.097 回答