我正在尝试将图像放入已从服务器检索的文件中。我正在使用fwrite
函数,但它并没有按照我想要的方式运行。看起来最大的问题是它无法写出\
字符。或者可能不是。我不知道该怎么做。有谁知道我做错了什么?提前谢谢。
这是我的fwrite代码:
FILE * pFile;
if((pFile = fopen ("test", "wb")) == NULL) error(1);
fwrite (buffer.c_str() , 1, buffer.size(), pFile);
其中buffer包含从服务器检索的数据。当它包含纯HTML时,它工作得很好。
这是我的输出:
GIF89a¥ÈÔ
这是它应该写的内容:
GIF89a\A5\C8\00
答案 0 :(得分:0)
fwrite()
不会自动执行您想要的转换。
您应该实现一些代码以将要转换的内容转换为“\
字符”。
示例:
#include <cstdio>
#include <string>
void error(int no) {
printf("error: %d\n", no);
exit(1);
}
int main(void) {
char data[] = "GIF89a\xA5\xC8"; // '\0' is automatially added after string literal
std::string buffer(data, sizeof(data) / sizeof(*data));
FILE * pFile;
// use text mode because it seems you want to print text
if((pFile = fopen ("test", "w")) == NULL) error(1);
for (size_t i = 0; i < buffer.size(); i++) {
if (0x20 <= buffer[i] && buffer[i] <= 0x7E && buffer[i] != '\\') {
// the data is printable ASCII character except for \
putc(buffer[i], pFile);
} else {
// print "\ character"
fprintf(pFile, "\\%02X", (unsigned char)buffer[i]);
}
}
fclose(pFile);
return 0;
}