動作環境
RAD Studio 10.2 Tokyo Update 3
概要
- バイナリ形式でのファイル書出し
- ファイルがないときは新規作成
- ファイルがあるときは追記
実装
Unit1.cpp
//---------------------------------------------------------------------------
# include <vcl.h>
# pragma hdrstop
# include "Unit1.h"
//---------------------------------------------------------------------------
# pragma package(smart_init)
# pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
char szbuf[20] = {0};
int pos;
strcat(szbuf, "hello");
pos = strlen(szbuf);
szbuf[pos++] =0x0A; // バイナリデータ
szbuf[pos++] =0x0B; // バイナリデータ
szbuf[pos++] =0x0C; // バイナリデータ
TFileStream *fstream;
static const String aFile = "test.bin";
if (FileExists(aFile)) {
fstream = new TFileStream(aFile, fmOpenReadWrite);
} else {
fstream = new TFileStream(aFile, fmCreate);
}
fstream->Seek(0, (int)soEnd); // (int): 関数の区別が曖昧を回避するため
fstream->WriteBuffer(szbuf, strlen(szbuf));
fstream->Free();
}
//---------------------------------------------------------------------------
TFileStream()のコンストラクタで処理を分岐しているが、一行でできる方がもっといいだろう。
関連
-
TFileStream.Create コンストラクタ (string, Word)
- RadStudio 2007の情報ではある