1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C++ Builder 10.2 Tokyo > バイナリファイル > 新規作成と追記

Last updated at Posted at 2019-11-22
動作環境
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()のコンストラクタで処理を分岐しているが、一行でできる方がもっといいだろう。

関連

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?