读书人

C++ builder 二进制方式读写字符串和图

发布时间: 2013-12-19 00:33:34 作者: rapoo

C++ builder 二进制形式读写字符串和图片
窗体上有控件
TImage image1

TEdit edit1,
怎么将 image1 和 edit1的内容以二进制的形式写到一个文件中
然后在以二进制的形式将image1 和edit1的信息读出来显示在窗体上
请高手指教。
[解决办法]
本帖最后由 ccrun 于 2012-04-11 18:36:46 编辑 下面是一个完整的简单的例程:
一开始初始化一下Image和Edit:

__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
Image1->Picture->LoadFromFile("D:\\ccrun\\123.bmp");
Edit1->Text = "测试数据abc好";
}


在Button1的点击事件中将Image中的位图和Edit中的文本内容写到指定的文件中:
// ---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
String strFileName = "D:\\ccrun\\123.ccrun";

// 打开或创建目标文件
int nFileHandle;
if (FileExists(strFileName))
nFileHandle = FileOpen(strFileName, fmOpenWrite);
else
nFileHandle = FileCreate(strFileName);

// 定位到文件头
FileSeek(nFileHandle, 0x0, 0);

// 将Image中的位图存入流中
TMemoryStream *ms = new TMemoryStream;
Image1->Picture->Bitmap->SaveToStream(ms);

// 先将图像流的大小写到文件中
DWORD dw = ms->Size;
FileWrite(nFileHandle, &dw, sizeof(dw));

// 再将图像流写到文件中
FileWrite(nFileHandle, ms->Memory, ms->Size);

// 接着写入Edit1中的文本长度
dw = Edit1->Text.Length();
FileWrite(nFileHandle, &dw, sizeof(dw));

// 再将Edit中的文本写入文件
FileWrite(nFileHandle, Edit1->Text.c_str(), Edit1->Text.Length());

delete ms;

FileClose(nFileHandle);
}


在Button2的点击事件中将Image和Edit清空:
void __fastcall TForm1::Button2Click(TObject *Sender)
{
Image1->Picture->Assign(NULL);
Edit1->Clear();
}


在Button3的点击事件中从文件中读取位图并显示在Image上,同时读取文本内容显示在Edit中:
void __fastcall TForm1::Button3Click(TObject *Sender)
{
String strFileName = "D:\\ccrun\\123.ccrun";

// 打开或创建目标文件
int nFileHandle;
if (FileExists(strFileName))
nFileHandle = FileOpen(strFileName, fmOpenRead);
else
{
ShowMessage("目标文件未找到.");
return;
}

// 定位到文件头
FileSeek(nFileHandle, 0x0, 0);

// 先读取图像流的大小
DWORD dw;
FileRead(nFileHandle, &dw, sizeof(dw));

// 根据图像流的大小,从文件中读取图像流
TMemoryStream *ms = new TMemoryStream;
byte *p = new byte[dw];
FileRead(nFileHandle, p, dw);
ms->Write(p, dw);
delete []p;

// 将图像流中的位图显示在Image上
ms->Position = 0;
Image1->Picture->Bitmap->LoadFromStream(ms);

// 接着读取文本的长度
FileRead(nFileHandle, &dw, sizeof(dw));

// 然后读取指定长度的内容到Edit中
char *str = new char[dw + 1];
FileRead(nFileHandle, str, dw);
str[dw] = 0x0;
Edit1->Text = str;

delete []str;

delete ms;



FileClose(nFileHandle);
}

读书人网 >C++ Builder

热点推荐