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

时间:2015-08-28 03:58:27

标签: c++ ifstream

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

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

1 个答案:

答案 0 :(得分:5)

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] = '\0'; //Add this

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

    return file; 
}