ifstream :: read不断返回不正确的值

时间:2015-08-05 12:30:13

标签: c++ fstream binaryfiles

我目前正在通过教自己如何使用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<<"\n\n";

“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;

该测试代码完美地编写和阅读。知道我做错了什么吗?感谢任何能指出我正确方向的人!

3 个答案:

答案 0 :(得分:3)

当您从中读取文件时,永远不会将文件重置为开头

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

答案 1 :(得分:1)

在尝试阅读之前,返回文件的开头是值得的:

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

答案 2 :(得分:0)

我认为问题在于你寻求最终获得文件大小,但在尝试读取文件之前不要回头。

相关问题