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

后端 未结 3 987
被撕碎了的回忆
被撕碎了的回忆 2021-01-02 00:35

I need to read a jpg file to a string. I want to upload this file to our server, I just find out that the API requires a string as the data of this pic. I followed the sugge

相关标签:
3条回答
  • 2021-01-02 00:50

    You shouldn't read the file to a string because it is legal for a jpg to contain values that are 0. However in a string, the value 0 has a special meaning (it's the end of string indicator aka \0). You should instead read the file into a vector. You can do this easily like so:

    #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;
    }
    
    0 讨论(0)
  • 2021-01-02 00:58

    Try opening the file in binary mode:

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

    At a guess, you were probably trying to read the file on Windows and the 61st character was probably 0x26 -- a control-Z, which (on Windows) will be treated as marking the end of the file.

    As far as how to best do the reading, you end up with a choice between simplicity and speed, as demonstrated in a previous answer.

    0 讨论(0)
  • 2021-01-02 01:00

    Open the file in binary mode, otherwise it will have funny behavior, and it will handle certain non-text characters in inappropriate ways, at least on Windows.

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

    Also, instead of a while loop, you can just read the whole file in one shot:

    ostrm << fin.rdbuf();
    
    0 讨论(0)
提交回复
热议问题