【发布时间】:2025-12-20 04:40:11
【问题描述】:
下面是我发现的一些代码,据我所知,这些代码读入二进制文件。我已经评论了我认为正在发生的事情,但是我无法识别 memblock 到底是什么/它正在存储什么。是整个二进制文件吗?
void BinaryFiles(string sfile){
streampos size; //creates object to store size of file
unsigned char* memblock;
ifstream file(sfile, ios::in | ios::binary); //creates file object(which opens file)
if (file.is_open())
{
file.seekg(0, ios::end); //find end of file
size = file.tellg(); //sets size equal to distance from beginning
memblock = new unsigned char[size]; //dynamically allocates memblock to char array
file.seekg(0, ios::beg); //find beginning of file
file.read((char*)memblock, size); //this is where confusion begins
cout << memblock << endl; //what am I printing?
file.close();
delete[] memblock;
}
}
【问题讨论】:
-
cout << memblock << endl; //what am I printing?好问题:从文件中读取的内容。但是,它可能不适合cout。想象一下,二进制文件中的第一个字节是0。然后,cout << memblock << endl;将只打印新行。对于任意二进制的输出,例如某种hexdump 是更好的选择。 -
看看文档。的std::istream::read()。第一个参数。是指向目标缓冲区(适当大小)的指针,第二个参数。是要读取的字符数。所以,是的,它会读取整个文件。
标签: c++ binaryfiles