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

Read a binary file (jpg) to a string using c++

本文关键字:读取 字符串 jpg c++ 二进制文件 使用      更新时间:2023-10-16

我需要将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;
}

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

更新

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

顺便问一下ifstream::binaryios::binary有什么区别,ofstream::binary有缩写吗?

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

ifstream fin("cloud.jpg", ios::binary);

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

ostrm << fin.rdbuf();

不应将文件读入字符串,因为 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;
}

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

ifstream fin("cloud.jpg", std::ios::binary);

猜测,您可能正在尝试在Windows上读取文件,并且第61个字符可能0x26 - 一个control-Z,(在Windows上(将被视为标记文件的末尾。

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