使用C++读取整个文件,忽略假阳性EOF
Reading an entire file using C++, ignoring false-positive EOFs
我正在做一个小的霍夫曼压缩加密程序,在文件解压缩过程中,我当前的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
相关文章:
- std::ifstream::read 不会读取所有 512 字节,并设置 EOF 和失败位
- 而(!inputfile.eof())只读取第一行?
- 如何在 EOF 之前从文件中读取并将其放入字符串中?
- 如何在从文件中读取整数时使用 file.eof()?
- std::cin 在读取 EOF 并清除后不再读取
- 读取 c++ istream 直到 EOF,同时丢弃内容
- 使用 gzread 读取直到 EOF 并膨胀浮点值
- Fstream 在点击 EOF 时读取行为
- .EOF 在读取文件时导致 Seg 错误:FIXXED
- 输入文件读取错误的值,eof 控制循环不会结束
- C OOP,读取文件的问题,EOF使用了两次,排行榜
- 为什么Windows不能读取超过0x1A(EOF)字符,而Unix可以?
- C++和 eof 中的文件读取
- 简单C++不读取EOF
- 如果用户输入字符串,请在用户中读取 n和eof
- std :: getline部分读取第一行,并设置eof-bit
- 在读取C 文件时跳过EOF
- 输入 EOF 后,不能重复使用 cin 来读取值
- EOF 位:读取失败之前或之后
- 如何在 EOF (C++) 之前读取多个块中的文件