convert a file (.txt,.pdf..) into a stream file

后端 未结 1 509
梦谈多话
梦谈多话 2021-01-29 15:18

I would like to ask what is the easiest and faster way to convert a file into a stream file.

I did the following :

//convert to stream:
std::string fil=          


        
相关标签:
1条回答
  • 2021-01-29 15:47

    As far as I know, the easiest way to read a file into a string (byte for byte) using only C++03 standard library facilities is:

    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <string>
    
    std::string readfile ( const std::string& path )
    {
        std::ostringstream contents;
        std::ifstream file(path.c_str(), std::ios::binary);
        contents << file.rdbuf();
        return (contents.str());
    }
    

    Then, you can proceed to whatever processing you want to apply:

    std::cout << readfile("foo.txt") << std::endl;
    

    If you want to apply base 64 encoding, I'll assume the following signature from your code, and a convenient overload:

    std::string base64_encode( const unsigned char * data, std::size_t size );
    
    std::string base64_encode ( const std::string& contents )
    {
        const unsigned char * data =
            reinterpret_cast<const unsigned char*>(contents.data());
        return (base64_encode(data, contents.size()));
    }
    

    Which you can invoke as such:

    // Read "foo.txt" file contents, then base 64 encode the binary data.
    const std::string data = base64_encode(readfile("foo.txt"));
    
    0 讨论(0)
提交回复
热议问题