Ifstream::read总是返回不正确的值

ifstream::read keeps returning incorrect value

本文关键字:不正确 返回 read Ifstream      更新时间:2023-10-16

我目前正在自学如何使用c++处理文件,并且我在从文件中提取二进制信息方面遇到了一些困难。

我代码:

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<<"nn";

"simplehashingfile.txt"文件只包含50字节的正常文本。大小被正确地确定为50字节,但是gcount返回0个字符读取,并且缓冲区输出(可以理解从gcount)是一个50行无内容的列表。

我怎么也想不出我哪里出错了!我之前编写了这个测试代码:

//  Writing binary to file
std::ofstream ofile;
ofile.open("testbinary", std::ios::out | std::ios::binary);
uint32_t bytes4 = 0x7FFFFFFF;  //  max 32-bit value
uint32_t bytes8 = 0x12345678;  //  some 32-bit value

ofile.write( (char*)&bytes4 , 4 );
ofile.write( (char*)&bytes8, 4 );
ofile.close();

//  Reading from file
std::ifstream ifile;
ifile.open("testbinary", std::ios::out | std::ios::binary);
uint32_t reading;  //  variable to read data 
uint32_t reading2;
ifile.read( (char*)&reading, 4 );
ifile.read( (char*)&reading2, 4 );
std::cout << "The file contains:  " << std::hex << reading << std::endl;
std::cout<<"next 4 bytes:  "<< std::hex << reading2 << std::endl;

测试代码写起来和读起来都很完美。知道我做错了什么吗?感谢任何能给我指出正确方向的人!

当你读取文件时,你永远不会将文件重置回开始

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

您需要再次调用seekg()并将文件指针重置回起点。使用

fille.seekg(0, std::ios::beg);

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

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

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

我认为问题是你做了一个查找到最后得到文件大小,但在试图读取文件之前没有查找到开始