C++ 读取二进制文件c++;
我正在尝试将图像读入字符数组。以下是我的尝试:C++ 读取二进制文件c++;,c++,file,binary,C++,File,Binary,我正在尝试将图像读入字符数组。以下是我的尝试: ifstream file ("htdocs/image.png", ios::in | ios::binary | ios::ate); ifstream::pos_type fileSize; char* fileContents; if(file.is_open()) { fileSize = file.tellg(); fileContents = new char[fileSize]; file
ifstream file ("htdocs/image.png", ios::in | ios::binary | ios::ate);
ifstream::pos_type fileSize;
char* fileContents;
if(file.is_open())
{
fileSize = file.tellg();
fileContents = new char[fileSize];
file.seekg(0, ios::beg);
if(!file.read(fileContents, fileSize))
{
cout << "fail to read" << endl;
}
file.close();
cout << "size: " << fileSize << endl;
cout << "sizeof: " << sizeof(fileContents) << endl;
cout << "length: " << strlen(fileContents) << endl;
cout << "random: " << fileContents[55] << endl;
cout << fileContents << endl;
}
谁能给我解释一下吗?位置8是否有文件结尾字符?这个例子取自
运行Mac OS X并使用XCode编译。我的另一个问题应该正是您想要的(特别是关于将其读入向量的第二部分,您应该更喜欢数组)
至于你的产出:
sizeof(fileContents)
返回char*
的大小,在您的系统上是8(我猜是64位)
strlen
在第一个'\0'
处停止,就像输出操作符一样
返回文件大小。image.png的大小为1944字节
cout您希望看到什么?png文件是二进制文件,因此它们可能在某个地方包含'\0'
字符(具有数值0的字符)
如果将png文件内容视为字符串('\0'终止字符数组
),并将其打印为字符串,则在遇到第一个'\0'
字符后,它将停止
因此代码没有问题,fileContents
正确地包含png文件(大小为1944字节)
fileSize—文件中的字节数
sizeof(fileContents)-返回char*指针的大小
strlen(fileContents)-计算字符数,直到找到值为“0”的字符。这显然是在8个字符之后-因为您正在读取二进制数据,所以这不是意外的结果
cout使用无符号字符处理二进制数据是一种很好的做法。
由于受支持字体的限制,随机选择的字符可能无法在控制台窗口中正确显示。此外,您还可以通过以十六进制打印来验证相同的内容,并在十六进制编辑器中打开相同的文件进行验证。请不要忘了删除使用后分配的内存。可能重复的“否”不会出现重复,OP面临的问题是不同的,在源代码中不是真正的问题(除了内存泄漏)但是在理解它的过程中,你没有说明你期望的输出是什么。我期望sizeof或length中的一个是1944,但是考虑到下面的评论,我现在看到它不是一个我可以得到的输出。我尝试改变图像是否成功读取到数组中。但是我现在看到它可能是。谢谢你让我明白。我理解我的逻辑错误。我试图验证我是否成功阅读了整个图像。谢谢!
size: 1944
sizeof: 8
length: 8
random: ?
?PNG
delete[] fileContents;
size: 1944 // the png is 1944 bytes
sizeof: 8 // sizeof(fileContents) is the sizeof a pointer (fileContents type is char*) which is 8 bytes
length: 8 // the 9th character in the png file is '\0' (numeric 0)
random: ? // the 56th character in the png file
?PNG // the 5th-8th character is not printable, the 9th character is '\0' so cout stop here
vector< char > fileContents;
{
ifstream file("htdocs/image.png", ios::in | ios::binary | ios::ate);
if(!file.is_open())
throw runtime_error("couldn't open htdocs/image.png");
fileContents.resize(file.tellg());
file.seekg(0, ios::beg);
if(!file.read(&fileContents[ 0 ], fileContents.size()))
throw runtime_error("failed to read from htdocs/image.png");
}
cout << "size: " << fileContents.size() << endl;
cout << "data:" << endl;
for( unsigned i = 0; i != fileContents.size(); ++i )
{
if( i % 65 == 0 )
cout << L"\n';
cout << fileContents[ i ];
}