读二进制文件的C ++ [英] Read binary file c++
问题描述
我试图读取图像到一个字符数组。这里是我的尝试:
ifstream的文件(htdocs中/ image.png的ios ::在| IOS ::二进制| IOS :: ATE);
ifstream的:: pos_type档案大小;
字符* fileContents;
如果(file.is_open())
{
档案大小= file.tellg();
fileContents =新的char [档案大小]
file.seekg(0,内部监督办公室::求);
如果(!file.read(fileContents,档案大小))
{
COUT<< 无法读取<< ENDL;
}
file.close(); COUT<< 大小:<<档案大小<< ENDL;
COUT<< sizeof的:&所述;&下;的sizeof(fileContents)LT;< ENDL;
COUT<< 长:<< strlen的(fileContents)LT;< ENDL;
COUT<< 随机:&所述;&下; fileContents [55]&下;&下; ENDL;
COUT<< fileContents<< ENDL;
}
这是输出:
尺寸:1944年
sizeof的:8
长度:8
随机?
?PNG
谁能解释这样对我?有结束的文件中的一个字符在第8位置?这个例子是从 cplusplus.com
拍摄在运行Mac OS X,并与X code编译。
-
返回文件的大小。大小你的
image.png
是1944年字节
。COUT<< 大小:<<档案大小<< ENDL;
-
返回
的sizeof(字符*)
,这是8
您的环境。 的注意任何指针的大小始终是在任何环境下是一样的。的COUT<< sizeof的:&所述;&下;的sizeof(fileContents)LT;< ENDL;
-
您正在阅读的文件是一个二进制文件,所以它可能包含
0
作为一个有效的数据。当您使用的strlen
,它返回的长度,直到0
遇到,这在你的文件的情况下8
。COUT<< 长:<< strlen的(fileContents)LT;< ENDL;
-
返回字符在
56的位置
(还记得数组索引从0开始)从文件开始的。COUT<< 随机:&所述;&下; fileContents [55]&下;&下; ENDL;
一个建议:
千万记住用来释放为 fileContents
动态内存分配:的
删除[] fileContents;
如果你不这样做,你最终会创建一个的内存泄漏的
I'm trying to read an image into a char array. Here is my try:
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;
}
And this is the output:
size: 1944
sizeof: 8
length: 8
random: ?
?PNG
Can anyone explain this to me? Is there an end-of-file char at position 8? This example was taken from cplusplus.com
Running Mac OS X and compiling with XCode.
Returns the size of the file. size of your
image.png
is1944 bytes
.cout << "size: " << fileSize << endl;
Returns the
sizeof(char*)
, which is8
on your environment. Note that size of any pointer is always the same on any environment.cout << "sizeof: " << sizeof(fileContents) << endl;
The file you are reading is a binary file so it might contain
0
as a valid data. When you usestrlen
, it returns the length until a0
is encountered, which in the case of your file is8
.cout << "length: " << strlen(fileContents) << endl;
Returns the character at the
56th location
(remember array indexing starts from 0) from start of file.cout << "random: " << fileContents[55] << endl;
A suggestion:
Do remember to deallocate the dynamic memory allocation for fileContents
using:
delete[] fileContents;
if you don't, you will end up creating a memory leak.
这篇关于读二进制文件的C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!