ifstream::read不断返回不正确的值 我现在正在通过自己的方式来教我如何用C++来处理文件,而且我从文件中提取二进制信息有一点困难。

ifstream::read不断返回不正确的值 我现在正在通过自己的方式来教我如何用C++来处理文件,而且我从文件中提取二进制信息有一点困难。,c++,fstream,binaryfiles,C++,Fstream,Binaryfiles,我的代码: std::string targetFile = "simplehashingfile.txt"; const char* filename = targetFile.c_str(); std::ifstream file; file.open( filename, std::ios::binary | std::ios::in ); file.seekg(0, std::ios::end); // go to end of file std::streamsize size

我的代码:

std::string targetFile = "simplehashingfile.txt";
const char* filename = targetFile.c_str();
std::ifstream file;

file.open( filename, std::ios::binary | std::ios::in );
file.seekg(0, std::ios::end);  //  go to end of file
std::streamsize size = file.tellg();  //  get size of file

std::vector<char> buffer(size);  //  create vector of file size bytes

file.read(buffer.data(), size);  //  read file into buffer vector
int totalread = file.gcount();

//  Check that data was read
std::cout<<"total read: " << totalread << std::endl;


//  check buffer:  
std::cout<<"from buffer vector: "<<std::endl;
for (int i=0; i<size; i++){
    std::cout << buffer[i] << std::endl;
}
std::cout<<"\n\n";
std::string targetFile=“simplehashingfile.txt”;
const char*filename=targetFile.c_str();
std::ifstream文件;
打开(文件名,std::ios::binary | std::ios::in);
seekg(0,std::ios::end);//转到文件末尾
std::streamsize size=file.tellg();//获取文件大小
标准::向量缓冲区(大小);//创建文件大小字节的向量
file.read(buffer.data(),size);//将文件读入缓冲区向量
int totalread=file.gcount();
//检查数据是否已读取

std::cout在读取文件时,永远不会将其重置回起始位置

std::streamsize size = file.tellg(); //<- goes to the end of the file
std::vector<char> buffer(size);  //  create vector of file size bytes

file.read(buffer.data(), size);  //<- now we read from the end of the file which will read nothing
int totalread = file.gcount();
以前

file.read(buffer.data(), size);

在读取文件时,永远不会将其重置回起始位置

std::streamsize size = file.tellg(); //<- goes to the end of the file
std::vector<char> buffer(size);  //  create vector of file size bytes

file.read(buffer.data(), size);  //<- now we read from the end of the file which will read nothing
int totalread = file.gcount();
以前

file.read(buffer.data(), size);

在尝试读取之前,请返回文件的开头:

file.seekg(0, std::ios::beg)

在尝试读取之前,请返回文件的开头:

file.seekg(0, std::ios::beg)

我认为问题在于,在尝试读取文件之前,您会一直搜索到文件的末尾以获取文件大小,但不会返回到开头。

我认为问题在于,您会一直搜索到末尾以获取文件大小,但在尝试读取文件之前,不会返回到开头