将任何类型的文件转换为带有c字符串的文件

时间:2009-11-10 19:02:45

标签: c++ c command-line file resources

请建议一个小型命令行实用程序(用于Windows)将文件从特定目录转换为有效的c文件。也许它可以用批处理命令完成? 生成的文件应如下所示:

static const unsigned char some_file[] = {
    /* some_file.html */
    0x2f, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x65, 0x73, 0x2e, 0x73, 0x68, 0x74, 0x6d, 0x6c, 0,
    0x25, 0x21, 0x3a, 0x20, 0x2f, 0x68, 0x65, 0x61, 0x64, 0x65
}

static const unsigned char some_other_file[] = {
    /* some_other_file.png*/
    0x2f, 0x34, 0x30, 0x34, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0,
    0x3c, 0x68, 0x74, 0x6d, 0x6c, 0x3e, 0xa, 0x20, 0x20, 0x3c
}

P.S。请不要建议Perl和Python端口。它们对于这项任务来说太沉重了。

P.P.S。可能有人知道比bin2h更可定制的实用程序,但是比awt更重,更复杂?哪个可以解析几个文件并将它们放到一个C中。同时指定自定义变量名称(使用某种索引文件)也很棒。所以它可以添加到构建过程中。

4 个答案:

答案 0 :(得分:13)

使用xxd -i file

我使用Vim附带的那个。例如:

C:\Documents and Settings\user> xxd -i error.log | head -n2
unsigned char error_log[] = {
  0x0c, 0x0d, 0x0a, 0x3d, 0x3d, 0x32, 0x30, 0x30, 0x39, 0x2f, 0x35, 0x2f,

另见Is it possible to view a binary in ones and zeros?

答案 1 :(得分:5)

Bin2h会这样做。

  

Bin2h - Win32二进制到C头文件   转换器

     

Win32命令行实用程序   将二进制文件转换为C语言   头文件,表示内容   该文件作为数据块。

我不相信输入文件必须是二进制文件。

答案 2 :(得分:3)

如果你想要一个可以自由使用的工具(商业或其他),这里是Adrian Prantl的GPL bin2c:

/*
 * bin2c: A Program to convert binary data into C source code
 * Copyright 2004 by Adrian Prantl <adrian@f4z.org>
 *
 *   This program is free software; you can redistribute it and/or modify  
 *   it under the terms of the GNU General Public License as published by  
 *   the Free Software Foundation; either version 2 of the License, or     
 *   (at your option) any later version.
 *
 */

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

char* self = 0;

void usage() {
    printf("Usage:\n%s input.bin output.h name\n\n", self);
}

void bail_out(const char* s1, const char* s2) {
    fprintf(stderr, "%s: FATAL ERROR:\n%s%s\n", self, s1, s2);
    exit(1);
}

int main(int argc, char** argv) {
    FILE *fi, *fo;
    int c, i;

    self = argv[0];

    if (argc != 4) {
        usage();
        return 0;
    }

    if ((fi = fopen(argv[1], "rb")) == 0)
        bail_out("Cannot open input file ", argv[1]);

    if ((fo = fopen(argv[2], "w")) == 0)
        bail_out("Cannot open output file ", argv[2]);

    if ((c = fgetc(fi)) != EOF) {
        fprintf(fo, "#ifndef %s_H\n", argv[3]);
        fprintf(fo, "#define %s_H\n\n", argv[3]);
        fprintf(fo, "const unsigned char %s[] = {\n", argv[3]);
        fprintf(fo, c < 16 ? "   0x%02x" : "    0x%02x", (unsigned char) c);
    }

    i = 1;
    while ((c = fgetc(fi)) != EOF) {
        if (i < 12)
            fprintf(fo, c < 16 ? ", 0x%02x" : ", 0x%02x", (unsigned char) c);
        else {
            fprintf(fo, c < 16 ? ",\n   0x%02x" : ",\n   0x%02x", (unsigned char) c);
            i = 0;
        }
        i++;
    }
    fprintf(fo, "\n};\n\n");
    fprintf(fo, "#endif\n");

    printf("converted %s\n", argv[1]);

    return 0;
}

这是一个70行左右的C文件 - 无需编译和运行。

答案 3 :(得分:0)

SRecord可以做到这一点,等等。虽然用C语言编写自己的单词并不困难。