Here's something I put together that should work:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
int infile = open(argv[1], O_RDONLY);
if (infile == -1) {
perror("open failed");
exit(1);
}
FILE *outfile = fopen(argv[2],"w");
if (!outfile) {
perror("fopen failed");
exit(1);
}
fprintf(outfile, "char %s[] = ", argv[3]);
int buflen;
int totallen, i, linelen;
char buf[1000];
totallen = 0;
linelen = atoi(argv[4]);
while ((buflen=read(infile, buf, sizeof(buf))) > 0) {
for (i=0;i<buflen;i++) {
if (totallen % linelen == 0) {
fprintf(outfile, "\"");
}
if (buf[i] == '\"' || buf[i] == '\\') {
fprintf(outfile,"\\%c",buf[i]);
} else if (isalnum(buf[i]) || ispunct(buf[i]) || buf[i] == ' ') {
fprintf(outfile,"%c",buf[i]);
} else {
fprintf(outfile,"\\x%02X",buf[i]);
}
if (totallen % linelen == linelen - 1) {
fprintf(outfile, "\"\n ");
}
totallen++;
}
}
if (totallen % linelen != 0) {
fprintf(outfile, "\"");
}
fprintf(outfile, ";\n");
close(infile);
fclose(outfile);
return 0;
}
Sample input:
This is a "test". This is only a \test.
Called as:
/tmp/convert /tmp/test1 /tmp/test1.c test1 10
Sample output
char test1[] = "This is a "
"\"test\". Th"
"is is only"
"a \\test.\x0A"
;