我正在尝试将图像读入char数组.这是我的尝试:
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;
}
Run Code Online (Sandbox Code Playgroud)
这是输出:
size: 1944
sizeof: 8
length: 8
random: ?
?PNG
Run Code Online (Sandbox Code Playgroud)
任何人都可以向我解释这个吗?8位是否有文件结尾的字符?此示例来自cplusplus.com
运行Mac OS X并使用XCode进行编译.
Alo*_*ave 10
返回文件的大小.你的大小image.png是1944 bytes.
cout << "size: " << fileSize << endl;
返回sizeof(char*),这是8您的环境.请注意,任何指针的大小在任何环境中始终相同.
cout << "sizeof: " << sizeof(fileContents) << endl;
您正在读取的文件是二进制文件,因此它可能包含0有效数据.使用时strlen,它会返回长度,直到0遇到a,在文件的情况下是8.
cout << "length: " << strlen(fileContents) << endl;
56th location从文件的开头返回(记住数组索引从0开始)的字符.
cout << "random: " << fileContents[55] << endl;
一条建议:
请记住取消分配动态内存分配以fileContents使用:
delete[] fileContents;
Run Code Online (Sandbox Code Playgroud)
如果不这样做,最终会造成内存泄漏.