텍스트 처리에 적합한 툴 소개 부탁드립니다.

freezm7의 이미지

.c 파일에 바이너리 파일을 넣을 때,

const unsigned char image[] = {
   0xf3, 0x2d, ...
}

의 c 파일을 만들기 위해, 지금은 파일 -> c 코드로 변환하는 xxd 같은 프로그램을 이용하고 있습니다.

그런데 이 방식이 바이너리 파일이 자꾸 바뀔 경우엔 상당히 불편합니다.

그래서, C 전처리기와 비슷한 프로그램(내지 스크립트)를 만들어 보려고 합니다.

const unsigned char image[] = {
#HEX a.c
}

== 위와 같은 파일을 프로그램으로 돌려서

const unsigned char image[] = {
  0xfe, 0x2d, ...
}

예전에 이런 프로그램이 있는지 질문을 올렸었는데,
아쉽게도 찾지 못했습니다.

그래서 제가 만들어 보려고 하는데, 세가지 정도 방법이 떠오르더군요.

(1) c 로 직접 작성한다.
(2) 텍스트 처리 전용 언어 (펄 등...) 을 사용한다.
(3) lex & yacc

이 중에서 현실적으로 제가 할 줄 아는 방법은 1번 밖에 없습니다.
하지만, 가능하다면 2번이나 3번 방법이 더 쉬울 것 같거든요.

2번 방법은 #HEX 등의 키워드를 찾기는 쉬울 것 같은데,
정작 인클루드(헥스 형식으로) 해야 할 파일을 처리하진 못할 것 같습니다.
3번 방법은 전혀 제가 모르는 쪽이구요. :cry:

2, 3번 쪽으로 잘 아시는 분의 가능성에 대한 조언 부탁드립니다.

만들어지면 물론 소스 공개하겠습니다. :D

cinsk의 이미지

m4를 쓰세요.

일단, 소스 파일(tmp.c.m4)은 다음과 같이 만들고..

m4_include(hexdump.m4)
#include <stdio.h>

const unsigned char image[] = {
  m4_hexdump([[hello.jpg]])
};

다음과 같이 hexdump.m4를 만듭니다.

m4_divert(-1)
m4_changequote([[,]])
m4_define([[m4_hexdump]], [[m4_esyscmd(cat $1 | xxd -i)]])
m4_divert

그리고 다음 명령을 수행해서 원하는 tmp.c를 얻습니다.

$ m4 -P tmp.c.m4 > tmp.c

출력 결과는:


#include <stdio.h>

const unsigned char image[] = {
  0x0a, 0x69, 0x6e, 0x74, 0x0a, 0x6d, 0x61, 0x69, 0x6e, 0x28, 0x76, 0x6f,
  0x69, 0x64, 0x29, 0x0a, 0x7b, 0x0a, 0x20, 0x20, 0x70, 0x72, 0x69, 0x6e,
  0x74, 0x66, 0x28, 0x22, 0x25, 0x64, 0x20, 0x68, 0x65, 0x6c, 0x6c, 0x6f,
  0x2c, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x22, 0x2c, 0x20, 0x5f, 0x5f,
  0x53, 0x54, 0x44, 0x43, 0x5f, 0x56, 0x45, 0x52, 0x53, 0x49, 0x4f, 0x4e,
  0x5f, 0x5f, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
  0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x30, 0x3b, 0x0a, 0x7d,
  0x0a, 0x0a

};

일일히 m4를 실행하는 건 귀찮으니, Makefile에 넣어 두는게 좋겠죠..

lsj0713의 이미지

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

int main(int argc, char *argv[])
{
    FILE *in, *out;
    int c;
    int count;

    if ( argc != 4 )
    {
        printf("\nUsage: bin2c input_filename output_filename variable_name\n");
        return EXIT_SUCCESS;
    }

    in = fopen(argv[1], "rb");
    if ( !in )
    {
        printf("\nError: Can't read file '%s'\n", argv[1]);
        return EXIT_FAILURE;
    }

    out = fopen(argv[2], "w");
    if ( !out )
    {
        printf("\nError: Can't write file '%s'\n", argv[2]);
        return EXIT_FAILURE;
    }

    printf("\nInput file: %s\nOutput file: %s\n", argv[1], argv[2]);

    fprintf(out, "const unsigned char %s[] = {\n\t", argv[3]);
    count = 0;

    while ( (c = fgetc(in)) != EOF )
    {
        fprintf(out, "0x%02x, ", c);
        ++count;
        if ( count % 8 == 0 ) { fprintf(out, "/* %d */\n\t", count); }
    }

    fprintf(out, "\n};\n");

    fclose(in);
    fclose(out);

    printf("\nSuccess!\n");

    return EXIT_SUCCESS;
}

bin2c image1.jpg image1.c image1 이라고 치면

const unsigned char image1 = { ... };

이런 소스코드가 image1.c란 파일 이름으로 생성됩니다.
그럼 필요한 곳에다가

#include "image1.c"

라고 쓰면 간단하지요. #include는 반드시 헤더파일에만 사용 가능한 것은 아닙니다. 단순한 '포함'일 뿐이기 때문에 소스 코드던 주석이던 뭐든지 가능합니다.

printf(
#include "a.txt"
);

---- a.txt ----
"Welcome!"

이런 것도 가능합니다.

ps. 가독성 면에서는 다음과 같이 하는 편이 낫겠군요.

---- 원래 코드 ----
const unsigned char image1 = {
#include "image1.txt"
};

---- image1.txt ----
0xaa, 0xab, ....
freezm7의 이미지

cinsk 님의 m4 를 이용한 방법이 제가 찾던 것이네요. 감사합니다.

여담이지만, lsj0713 님의

lsj0713 wrote:

bin2c image1.jpg image1.c image1 이라고 치면
const unsigned char image1 = { ... };

이런 소스코드가 image1.c란 파일 이름으로 생성됩니다.
그럼 필요한 곳에다가

#include "image1.c"

라고 쓰면 간단하지요. #include는 반드시 헤더파일에만 사용 가능한 것은 아닙니다. 단순한 '포함'일 뿐이기 때문에 소스 코드던 주석이던 뭐든지 가능합니다.

는 xxd 와 쉘변수를 이용해서 다음과 같이 구현할 수도 있겠네요.

xxd -i image.jpg > image.tmp1
line=`wc -l image.tmp1 | awk '{print $1}'`
head -n `expr $line - 2` image.tmp1 > image.tmp2
tail -n `expr $line - 3` > image.c
rm tmp1 tmp2

즐겁게 살아 볼까나~*

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.