Dáta v spustiteľnej binárke

Príklad, ako vytvoriť program, ktorý bude v sebe obsahovať dáta nejakého súboru.

Súbory edit

Licencia súborov: CC0.

hello_world.txt edit

Hello world

file_to_inline.php edit

Zo vstupného súboru vytvorí C hlavičkový súbor, ktorý sa následne použije v zdrojovom kóde programu. Vstupný súbor môže byť textový aj binárny súbor.

<?php

if($argc != 2)
{
	fwrite(STDERR, $argv[0]." FILE\n");
	return 1;
}
$file=file_get_contents($argv[1]);
if($file === false)
{
	fwrite(STDERR, "Error open/read the file '".$argv[1]."'\n");
	return 1;
}

$output_file=str_replace(".", "_", $argv[1]);
$output="#ifndef ${output_file}_H\n";
$output.="#define ${output_file}_H\n";
$output.="const void *inline_${output_file}_data=\"";
$input_length=strlen($file);
for($i=0;$i<$input_length;$i++)
	$output.="\\x".strtoupper(bin2hex($file[$i]));
$output.="\";\n";
$output.="const size_t inline_${output_file}_size=$input_length;\n";
$output.="#endif\n";

file_put_contents($output_file.".h", $output);

test.c edit

#include <stdio.h>

#include "hello_world_txt.h"

int main()
{
	puts(inline_hello_world_txt_data);
	
	return 0;
}

Otestovanie edit

# vytvorí súbor hello_world_txt.h
php file_to_inline.php hello_world.txt

cc test.c -o test

$ ./test 
Hello world

Pozri aj edit