C ++ ifstream在从文本文件读取时附加垃圾数据

C++ ifstream appending garbage data while reading from a text file

char* readFromFile(char* location)
{
    int total = 0;
    ifstream ifile = ifstream(location);
    ifile.seekg(0, ifile.end);
    total = ifile.tellg();

    cout << "Total count" << total << endl;
    char* file = new char[total+1];

    ifile.seekg(0, ifile.beg);

    ifile.read(file, total+1);

    cout <<"File output" << endl<< file << "Output end"<<endl;

    return file;
}

这里它正在打印文件数据,但它也附加了一些垃圾值。我该如何解决?

read 只是读取一些字节,它不会空终止序列。虽然 cout 需要一个空终止序列,因此它会继续打印位于数组之后的随机内存,直到遇到 0。因此您需要分配一个额外的字符,然后用空字符填充它。

char* readFromFile(char* location)
{
    int total = 0;
    ifstream ifile = ifstream(location);
    ifile.seekg(0, ifile.end);
    total = ifile.tellg();

    cout << "Total count" << total << endl;
    char* file = new char[total+1];

    ifile.seekg(0, ifile.beg);

    ifile.read(file, total); //don't need the +1 here

    file[total] = '[=10=]'; //Add this

    cout <<"File output" << endl<< file << "Output end"<<endl;

    return file; 
}