Visual c++ seekg()给出了奇怪的结果

Visual c++ seekg()给出了奇怪的结果,visual-c++,Visual C++,从中提取的以下代码块在我的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 l

从中提取的以下代码块在我的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;
}
//将文件读入内存
#include//std::cout
#include//std::ifstream
int main(){
std::ifstream是(“test.txt”,std::ifstream::binary);
如果(是){
//获取文件的长度:
is.seekg(0,is.end);
int length=is.tellg();
is.seekg(0,is.beg);
//分配内存:
字符*缓冲区=新字符[长度];
//将数据作为块读取:
is.read(缓冲区、长度);
is.close();
//打印内容:
std::cout.write(缓冲区、长度);
删除[]缓冲区;
}
返回0;
}

例如,当test.txt的内容为“hello\n”时,
length
的值为
2
。为什么会发生这种情况?

您实际打开的任何文件都不包含“hello\n”。不管怎么说,它永远不会出现在Windows上。它可能只包含“\r\n”。标准错误,请始终使用文件的完整路径名。感谢您的回复。我给出了完整的路径名,但是
length
仍然是
2
。当我使用
get()
从文件中逐个字符读取
length
时,我得到了
h
e
。发生了什么事?你的Visual Studio版本和我的不一样。或者我怀疑其他人。但我们不知道它是什么,所以只是猜测而已。