我见过的示例代码似乎使用标准的C文件输出函数,但我想用C ++编写。
我尝试使用fsteam函数来执行此操作,但根本没有数据写入.bmp文件。
到目前为止,我已经尝试过标准<<,put和write,而这些都没有。如果我用十六进制编辑器打开它,文件仍然是空的。
这很奇怪,因为输入函数工作正常。
这是我用来测试代码是否有效的代码:
output.open("WHITE.bmp");
output.put('B'); // this doesn't seem to work, the file is empty when I open it in a hex editor.
output.put('M');
其余的代码:
#include <iostream>
#include <fstream>
using namespace std;
typedef unsigned char byte;
typedef unsigned short dbyte;
struct BMPINFO
{
int width;
int height;
};
int main()
{
ifstream sourcefile;
ofstream output;
int threshold = 150;
sourcefile.open("RED.bmp");
if(sourcefile.fail())
{
cout << "Could not open RED.bmp" << endl;
return 1;
}
if(sourcefile.get() == 'B')
{
if(sourcefile.get() == 'M')
{
cout << "RED.bmp is a valid .bmp file" << endl;
}
}
else
{
cout << "RED.bmp is not a valid .bmp file" << endl;
return 1;
}
BMPINFO image;
// seeks to bitmap width, this file is little end in.
sourcefile.seekg (0x12, ios::beg);
unsigned int i = (unsigned)sourcefile.get();
i += (unsigned)sourcefile.get() << 8;
image.width = i;
cout << "The width of the image is: " << image.width << endl;
sourcefile.seekg (0x16, ios::beg);
i = sourcefile.get();
i += (unsigned)sourcefile.get() << 8;
image.height = i;
cout << "The height of the image is: " << image.height << endl;
int loc_pixels;
sourcefile.seekg (0x0A, ios::beg);
loc_pixels = sourcefile.get();
cout << "Location of pixel array is: " << loc_pixels << endl;
output.open("WHITE.bmp");
output.put('B'); // this doesn't seem to work, the file is empty when I open it in a hex editor.
output.put('M');
if(output.bad())
{
cout << "the attempt to output didn't work" << endl;
return 1;
}
sourcefile.seekg(loc_pixels, ios::beg);
char data[30000];
output.close();
return 0;
}
我应该使用特殊功能输出到这个.bmp文件吗?
编辑 - 添加了更多代码,但大多数代码与文件输出无关
答案 0 :(得分:4)
此代码中存在缓冲区溢出错误:
char data[30000]; // Prepare file for usage -- just copy one thing from the file to the other
sourcefile.read(data, image.height * image.width );
您正在读取image.height*image.width
个字节,并尝试将它们放入30000
个字节。您应该构建代码,以便这两个数字相关。
试试这个:
std::vector<char> data(image.height * image.width);
sourcefile.read(&data[0], data.size());
答案 1 :(得分:1)
有一个很棒的描述here。
ofstream myfile;
myfile.open("WHITE.bmp", ios::out | ios::binary); // opening in binary mode
myfile << 'B';
myfile << 'M';
myfile.close();