使用c ++将二进制文件(jpg)读取为字符串

zou*_*yjs 10 c++ file-io file-upload

我需要将jpg文件读取为字符串.我想将此文件上传到我们的服务器,我只是发现API需要一个字符串作为此图片的数据.我在之前的问题中遵循了这些建议,我已经使用c ++将上传图片到服务器.

int main() {
    ifstream fin("cloud.jpg");
    ofstream fout("test.jpg");//for testing purpose, to see if the string is a right copy
    ostringstream ostrm;

    unsigned char tmp;
    int count = 0;
    while ( fin >> tmp ) {
        ++count;//for testing purpose
        ostrm << tmp;
    }
    string data( ostrm.str() );
    cout << count << endl;//ouput 60! Definitely not the right size
    fout << string;//only 60 bytes
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么它停在60?60岁时这是一个奇怪的角色,我该怎么做才能将jpg读成一个字符串?

UPDATE

几乎在那里,但在使用建议的方法后,当我将字符串重写为输出文件时,它会失真.发现我还应该指定ofstream处于二进制模式ofstream::binary.完成!

那么ifstream::binary&之间的区别ios::binary是什么ofstream::binary?是否有缩写?

Ben*_*ley 18

以二进制模式打开文件,否则会产生有趣的行为,它会以不适当的方式处理某些非文本字符,至少在Windows上是这样.

ifstream fin("cloud.jpg", ios::binary);
Run Code Online (Sandbox Code Playgroud)

此外,您可以一次性读取整个文件,而不是while循环:

ostrm << fin.rdbuf();
Run Code Online (Sandbox Code Playgroud)


Bor*_*der 7

您不应该将文件读取为字符串,因为jpg包含值为0是合法的.但是在字符串中,值0具有特殊含义(它是字符串指示符的结尾,即\ 0).您应该将文件读入矢量.你可以这样轻松地做到这一点:

#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>

int main(int argc, char* argv[])
{
    std::ifstream ifs("C:\\Users\\Borgleader\\Documents\\Rapptz.h");

    if(!ifs)
    {
        return -1;
    }

    std::vector<char> data = std::vector<char>(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());

    //If you really need it in a string you can initialize it the same way as the vector
    std::string data2 = std::string(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());

    std::for_each(data.begin(), data.end(), [](char c) { std::cout << c; });

    std::cin.get();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Jer*_*fin 6

尝试以二进制模式打开文件:

ifstream fin("cloud.jpg", std::ios::binary);
Run Code Online (Sandbox Code Playgroud)

在猜测,你很可能试图读取Windows中的文件和61 字符可能是0×26 -控制-Z,它(在Windows上)会被当作标记文件的末尾.

至于如何最好地进行阅读,您最终会在简单性和速度之间做出选择,如之前的答案所示.