I am trying to put an image into a file that has been retrieved from a server. I am using the fwrite
function, but it doesn't really work the way I want it to. It looks like the biggest problem is that it can't write the \
character. Or maybe not. I don't know what to do with it. Does anyone know what am I doing wrong? Thanks in advance.
Here is my fwrite code:
FILE * pFile;
if((pFile = fopen ("test", "wb")) == NULL) error(1);
fwrite (buffer.c_str() , 1, buffer.size(), pFile);
where buffer contains data retrieved from server. When it contains pure html, it works just fine.
Here is my output:
GIF89a¥ÈÔ
Here is what it was supposed to write:
GIF89a\A5\C8\00
fwrite()
won't automatically do the conversion you want.
You should implement some code to convert what you want to convert to "\
character".
example:
#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;
}