bate's blog

調べたこと実装したことなどを取りとめもなく書きます。

perlとCでバイナリ

頻繁に使うテーブルのバイナリ化の簡単なメモを残しておくことにした。

perlでテキストのリストをバイナリにして、
Cでそのバイナリを読み込み、プリントしてみる。

下記を実行するとlist.binができる。
./txt2bin.pl list.txt

下記でlist.binの内容を表示する。
bin_viewer.exe list.bin

出力

0 --------------
name = nanashi
job = neet
age = 28
1 --------------
name = nashina
job = engineer
age = 45
2 --------------
name = shinana
job = 
age = 33

list.txt

nanashi,neet,28
nashina,engineer,45
shinana,,33

txt2bin.pl

#!/bin/perl

use strict;
use warnings;

# open to read 
open(INFILE,'<',$ARGV[0])||die("file open error :$ARGV[0], $!");

# open to write by bin
my $bin_file = $ARGV[0]; 
$bin_file =~ s/\..*$/\.bin/g;
open(OUTFILE,'>',$bin_file)||die("file open error : $bin_file, $!");
binmode OUTFILE;

# read list.txt
while( <INFILE> )
{
	chomp($_);
	my @data = split(/,/, $_);
	print OUTFILE pack("a16", $data[0]); #name
	print OUTFILE pack("a16", $data[1]); # job
	print OUTFILE pack("I",   $data[2]); # age
}

close(OUTFILE);
close(INFILE);

bin_viewer.cpp

#include <stdio.h>
#include <stdlib.h>

struct sPerson
{
	char name[16];
	char job[16];
	int age;
};

int main(int argc, char* argv[])
{
	FILE* fp = fopen(argv[1], "rb");
	if(fp==NULL) {
		perror(argv[1]);
		return 1;
	}
	sPerson person[3];
	fread((void*)person,1, sizeof(person), fp);
	
	for(int i = 0; i < 3; ++i) {
		printf("%d --------------\n",i);
		printf("name = %s\n", person[i].name);
		printf("job = %s\n", person[i].job);
		printf("age = %d\n", person[i].age);
	}
	fclose(fp);
	return 0;
}