2011-08-29 169 views
-3

我想問問什麼是將文件轉換爲流文件最簡單快捷的方法。將文件(.txt,.pdf ..)轉換爲流文件

我做了以下內容:

//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(); 

這是最簡單的方法?是否有可升級我的代碼?

編輯

代碼適用於.cpp或.txt文件。它不適用於.pdf文件。爲什麼?

+6

我想不通的問題是什麼。 – nothrow

+2

什麼是流文件,在這裏做什麼base64? – PlasmaHH

+0

我也使用base64編碼。我想將文件轉換爲字符串 – sunset

回答

0

據我知道,文件讀入一個字符串僅使用C++ 03標準庫(逐字節),最簡單的方法是:

#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()); 
} 

然後,就可以進行任何處理要應用:

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

如果要應用基地64編碼,我會認爲從您的代碼如下簽名,和方便的過載:

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())); 
} 

,你可以調用這樣:

// Read "foo.txt" file contents, then base 64 encode the binary data. 
const std::string data = base64_encode(readfile("foo.txt"));