2 * Copyright 2007, Ingo Weinhold <bonefish@cs.tu-berlin.de>.
3 * All rights reserved. Distributed under the terms of the MIT License.
16 write_string(int fd
, const char* data
)
18 int len
= strlen(data
);
22 ssize_t written
= write(fd
, data
, len
);
24 fprintf(stderr
, "Error: Failed to write to output file: %s\n",
32 main(int argc
, const char* const* argv
)
36 "Usage: %s <data var name> <size var name> <input> <output>\n",
40 const char* dataVarName
= argv
[1];
41 const char* sizeVarName
= argv
[2];
42 const char* inFileName
= argv
[3];
43 const char* outFileName
= argv
[4];
46 int inFD
= open(inFileName
, O_RDONLY
);
48 fprintf(stderr
, "Error: Failed to open input file \"%s\": %s\n",
49 inFileName
, strerror(errno
));
53 int outFD
= open(outFileName
, O_WRONLY
| O_CREAT
| O_TRUNC
,
54 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IROTH
);
56 fprintf(stderr
, "Error: Failed to open output file \"%s\": %s\n",
57 outFileName
, strerror(errno
));
61 const int kCharsPerLine
= 15;
62 const int kBufferSize
= 16 * 1024;
63 unsigned char buffer
[kBufferSize
];
66 sprintf(lineBuffer
, "#include <stddef.h>\n");
67 write_string(outFD
, lineBuffer
);
68 sprintf(lineBuffer
, "const unsigned char %s[] = {\n", dataVarName
);
69 write_string(outFD
, lineBuffer
);
72 char* lineBufferEnd
= lineBuffer
;
73 *lineBufferEnd
= '\0';
76 ssize_t bytesRead
= read(inFD
, buffer
, kBufferSize
);
78 fprintf(stderr
, "Error: Failed to read from input file: %s\n",
86 for (int i
= 0; i
< bytesRead
; i
++, offset
++) {
87 if (offset
% kCharsPerLine
== 0) {
89 // line is full -- flush it
90 strcpy(lineBufferEnd
, ",\n");
91 write_string(outFD
, lineBuffer
);
92 lineBufferEnd
= lineBuffer
;
93 *lineBufferEnd
= '\0';
96 sprintf(lineBufferEnd
, "\t%u", (unsigned)buffer
[i
]);
98 sprintf(lineBufferEnd
, ", %u", (unsigned)buffer
[i
]);
100 lineBufferEnd
+= strlen(lineBufferEnd
);
104 // flush the line buffer
105 if (lineBufferEnd
!= lineBuffer
) {
106 strcpy(lineBufferEnd
, ",\n");
107 write_string(outFD
, lineBuffer
);
110 // close the braces and write the size variable
111 sprintf(lineBuffer
, "};\nconst size_t %s = sizeof(%s);\n", sizeVarName
,
113 write_string(outFD
, lineBuffer
);