seekg()给出了奇怪的结果

时间:2016-03-10 07:26:00

标签: visual-c++

http://www.cplusplus.com/reference/istream/istream/seekg/中提取的以下代码块在我的Visual Studio版本中无法正常工作。

// 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);

    // allocate memory:
    char * buffer = new char [length];

    // read data as a block:
    is.read (buffer,length);

    is.close();

    // print content:
    std::cout.write (buffer,length);

    delete[] buffer;
  }

  return 0;
}

例如,当test.txt包含内容&#34; hello \ n&#34;时,length的值为2。为什么会这样?

0 个答案:

没有答案