使用C++读取整个文件,忽略假阳性EOF

Reading an entire file using C++, ignoring false-positive EOFs

本文关键字:EOF 读取 C++ 文件 使用      更新时间:2023-10-16

我正在做一个小的霍夫曼压缩加密程序,在文件解压缩过程中,我当前的getFile方法(应该将整个文件作为字符串返回)比预期的更快结束,并且试图在假阳性EOF(可能?它与同一字符串一致)后强制它读取会导致程序崩溃。

这是我目前的方法:

string getFile(string route){
    ifstream reader; 
    string s=""; 
    reader.open(route); 
    if(reader.bad())return "FAILURE TO OPEN FILE"; 
    reader.read((char*)&dictionary.weight, sizeof(int)); // There's an int in the beggining
    // It describes the original ammount of chars there were in the original file. 
    while(!reader.eof()){ s+= reader.get() } 
    reader.close(); 
    return s; 
}

您应该以二进制模式打开文件。这意味着不应该在文件的内容和程序看到的内容之间执行任何转换。默认情况称为文本模式,可能会发生各种转换;例如在Windows中,通常rn被转换为n,并且字节26可能看起来是文件的末尾。

reader.open(route, ios::binary);

此外,不要在循环条件中使用eof