简体   繁体   English

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

here it is printing the file data but it also appending some garbage value. 在这里,它正在打印文件数据,但它还附加了一些垃圾值。 how should I fix it? 我该如何解决?

read just reads a number of bytes, it doesn't null terminate the sequence. read只是读取多个字节,它不为null终止序列。 While cout expects a null terminated sequence, so it continues to print random memory that is located after your array until it runs into a 0. So you need to allocate one extra character, and then fill it with a null character. 尽管cout期望终止序列为null,所以它将继续打印位于数组之后的随机内存,直到遇到0。因此,您需要分配一个额外的字符,然后将其填充为null字符。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM