17
21

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言語でバイナリデータを扱う

Posted at

今までバイナリデータを直に扱うことがなかったので、C言語でごにょごにょしてみたのでメモ。

試したこと

とりあえず、バイナリの読み書きをする関数を使ってデータの保存と復元をしてみました。

サンプルコード

write-binary
# include <stdio.h>

int main() {
	struct Vector {
		float x;
		float y;
		float z;
	} position;
	
	FILE *fp;
	
	if ((fp = fopen("vectordata.dat", "wb+")) == NULL) {
		printf("Can't open a file.");
		return 1;
	}
	
	printf("X座標?");
	scanf("%f", &position.x);
	
	printf("Y座標?");
	scanf("%f", &position.y);
	
	printf("Z座標?");
	scanf("%f", &position.z);
	
	fwrite(&position, sizeof(position), 1, fp);
	fclose(fp);
}
read-binary
# include <stdio.h>

int main() {
	struct Vector {
		float x;
		float y;
		float z;
	} position;
	
	FILE *fp;
	
	if ((fp = fopen("vectordata.dat", "rb")) == NULL) {
		printf("Can't open a file.");
		return 1;
	}
	
	fread(&position, sizeof(position), 1, fp);
	fclose(fp);
	
	printf("X: %f\n", position.x);
	printf("Y: %f\n", position.y);
	printf("Z: %f\n", position.z);
	
	return 0;
}

実行結果

X: 15.000000
Y: 30.000000
Z: 45.000000

fwrite/fread関数

やっていることは単純に構造体に数値を入れて、それをfwrite関数で書き出し、fread関数で読み込んでいるだけです。

ライブラリ

stdio.h

【書式】

size_t fwrite(const void *buf, size_t size, size_t n, FILE *fp); 
引数 説明
buf 書き込むデータのポインタです。
size 書き込むデータのサイズです。(sizeofで計算して渡す)
n 実際に書き込むデータの数です。(e.g.) int型で10個の要素の配列なら10

fread関数も基本的に同じ引数でバイナリデータを読み込みます。

ちなみに書き込んだファイルの内容はodコマンドを利用することでバイナリの状態を出力することができます。

$ od -x vectordata.dat
0000000      0000    4170    0000    41f0    0000    4234
0000014
17
21
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
17
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?