C++ 以二进制模式读取文件。文件结尾问题

sme*_*its 3 c++ linux io binaryfiles

我正在学习 C++,我必须以二进制模式读取文件。我的做法如下(遵循 C++ 参考):

unsigned values[255];
unsigned total;
ifstream in ("test.txt", ifstream::binary);

while(in.good()){
    unsigned val = in.get();
    if(in.good()){
        values[val]++;
        total++;
        cout << val <<endl;
    }
}

in.close();
Run Code Online (Sandbox Code Playgroud)

所以,我正在逐字节读取文件,直到in.good()为真。我cout在末尾添加了一些内容,while以便了解发生了什么,这是输出:

marco@iceland:~/workspace/huffman$ ./main 
97
97
97
97
10
98
98
10
99
99
99
99
10
100
100
10
101
101
10
221497852
marco@iceland:~/workspace/huffman$
Run Code Online (Sandbox Code Playgroud)

现在,输入文件“test.txt”只是:

aaaa
bb
cccc
dd
ee
Run Code Online (Sandbox Code Playgroud)

所以一切都很完美,直到最后,也就是 221497852。我猜这是关于文件末尾的问题,但我无法找出问题所在。

我在 debian 机器(64 位)上使用 gedit 和 g++。任何帮助将不胜感激。

非常感谢,

马可

bas*_*h.d 5

fstream::get返回一个int- 值。这是问题之一。

其次,您正在以二进制方式阅读,因此不应使用格式化流。你应该使用fstream::read

// read a file into memory
#include <iostream>     // std::cout
#include <fstream>      // std::ifstream

int main () {

  std::ifstream is ("test.txt", std::ifstream::binary);
  if (is) {
    // get length of file:
    is.seekg (0, is.end);
    int length = is.tellg();
    is.seekg (0, is.beg);

    char * buffer = new char [length];

    std::cout << "Reading " << length << " characters... ";
    // read data as a block:
    is.read (buffer,length);

    if (is)
      std::cout << "all characters read successfully.";
    else
      std::cout << "error: only " << is.gcount() << " could be read";
    is.close();

    // ...buffer contains the entire file...

    delete[] buffer;
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)