Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Image 将图像写入文件-输出错误_Image_Fwrite - Fatal编程技术网

Image 将图像写入文件-输出错误

Image 将图像写入文件-输出错误,image,fwrite,Image,Fwrite,我试图将一个图像放入一个从服务器检索到的文件中。我正在使用fwrite函数,但它并没有按照我想要的方式工作。看起来最大的问题是它不能写\字符。也许不是。我不知道该怎么办。有人知道我做错了什么吗?提前谢谢 这是我的密码: FILE * pFile; if((pFile = fopen ("test", "wb")) == NULL) error(1); fwrite (buffer.c_str() , 1, buffer.size(), pFile); 其中缓冲区包含从服务器检索的数据。当它包含

我试图将一个图像放入一个从服务器检索到的文件中。我正在使用
fwrite
函数,但它并没有按照我想要的方式工作。看起来最大的问题是它不能写
\
字符。也许不是。我不知道该怎么办。有人知道我做错了什么吗?提前谢谢

这是我的密码:

FILE * pFile;
if((pFile = fopen ("test", "wb")) == NULL) error(1);
fwrite (buffer.c_str() , 1, buffer.size(), pFile);
其中缓冲区包含从服务器检索的数据。当它包含纯html时,它工作得很好

以下是我的输出:

GIF89a¥ÈÔ
下面是它应该写的内容:

GIF89a\A5\C8\00
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;
}
#包括
#包括
无效错误(整数编号){
printf(“错误:%d\n”,否);
出口(1);
}
内部主(空){
字符数据[]=“GIF89a\xA5\xC8”/“\0”自动添加到字符串文字后
字符串缓冲区(数据,sizeof(数据)/sizeof(*数据));
文件*pFile;
//使用文本模式,因为您似乎想要打印文本
如果((pFile=fopen(“test”,“w”))==NULL)错误(1);
对于(size_t i=0;i如果(0x20<代码>缓冲区.siz())/c>不象C代码。如果你使用C++,使用C++编码风格。是的。我用C++来编写它,因为字符串函数。为什么你要用<代码>缓冲区?CyString()/<代码>(即文本)来写二进制数据(图像文件内容)?您现在得到的输出更像文件应该包含的内容(如果您将二进制数据显示为文本)当你想要的输出不是有效的图像文件内容时,你用C标签代替C++标签来让事情变得更有趣?我删除C标签。只需添加C++标签。为什么不使用IOFSUBLE?我已经尝试过了。现在我的输出看起来像:GIF89A\A5\\C8\9A\D4\,所以格式是正确的,但不是所有的值都是。