gpt4 book ai didi

c - 使用 C 样式转义序列转义二进制文件

转载 作者:行者123 更新时间:2023-11-30 18:51:57 25 4
gpt4 key购买 nike

我有一个小的二进制文件。我想将该二进制文件作为字符数组导入到 C 程序中,如下所示:

char some_binary_data[] = "\000-type or \xhh-type escape sequences and such here";

是否有一个标准的 shell 命令可以使用 C 风格转义来呈现二进制数据?如果我可以在八进制样式转义和十六进制样式转义之间进行选择,那就加分了。

例如,如果我的文件包含字节

0000000 117000 060777 000123
0000006

,我想将其渲染为 "\000\236\377a\123" .

最佳答案

这是我整理的应该有效的东西:

#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;
}

示例输入:

This is a "test".  This is only a \test.

称为:

/tmp/convert /tmp/test1 /tmp/test1.c test1 10

示例输出

char test1[] = "This is a "
"\"test\". Th"
"is is only"
"a \\test.\x0A"
;

关于c - 使用 C 样式转义序列转义二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35512220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com