Ifstream::read总是返回不正确的值
ifstream::read keeps returning incorrect value
我目前正在自学如何使用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)
我认为问题是你做了一个查找到最后得到文件大小,但在试图读取文件之前没有查找到开始
相关文章:
- 在C++中返回不正确的楼层函数值
- 我的动态链接队列在同一输出流中调用时不正确地输出三个返回函数
- wcslen() 在使用编译指示包时返回不正确的结果
- 乘法返回我的值不正确
- 为什么代码不能返回正确的值?
- 派生类继承的 getter,找不到返回正确值的方法
- 返回类型不正确
- 当我输入分数值时,它返回不正确的结果
- ifstream::read 不断返回不正确的值
- Strftime在iOS上返回一周中不正确的一天
- C++ 中的 MD5 实现返回不正确的摘要
- AccessibleObjectFromPoint() 返回一个不正确的对象
- C 程序不会返回正确的阶乘值
- C 从文件中读取FSTREAM数据不会返回正确的值.inputfile.tellg返回-1
- MSVC OSVersion 返回不正确的版本
- C++ GetModule文件名不会返回正确的字符串
- 'SystemParametersInfo'函数在获取桌面壁纸时返回不正确的值
- 创建 CTime @ 2am 不会返回正确的值(Windows CE,C++)
- c++winsock-recv()返回不正确且奇怪的缓冲区
- Winsock recv() 返回不正确的数据