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

2019-03-07 16:32发布

问题:

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= "/home/file.pdf";

std::ifstream t(fil.c_str());
if (t)
{
  string res;
  string line;
  while (getline(t, line, '\n'))
  {
    res=res+line;
  }
  std::string p;
  p=(base64_encode((reinterpret_cast<const unsigned char *> (res.c_str())),res.size()));
  std::string data=p;

  char *token = strtok( const_cast<char*>(fil.c_str() ), "/" );
  std::string name;
  std::vector<int> values;

  while ( token != NULL )
  {
    name=token;
    token = strtok( NULL, "/" );
  }
  std::string f_name=name;
}

//convert from stream to file
ofstream myfile;

std::string fil;

ofstream file (fil.c_str(), ios::out | ios::binary);
std::string content = base64_decode(f_data);
file.write ((char*)&content, sizeof(content));
file.close();

Is this the easiest way?! Is there a posibility to upgrade my code?

EDIT

Code works for .cpp or .txt files. It doesn't work for .pdf files. why?

回答1:

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"));