2012-09-09 34 views
3

我使用NDK C++組件編寫Android項目,並且需要大量解析的文件。 NDK只允許我獲得一個指向我正在處理的文件的FILE *指針,而不是具有與其相關的更多便利功能的ifstream。反正有沒有將FILE *(cstdio)轉換爲ifstream(iostream)?將FILE *轉換爲ifstream C++,Android NDK

回答

3

請注意,沒有辦法檢索std::ifstream,但您可以得到std::istream

儘管不是標準C++的一部分,但有時std::basic_filebuf通過constructor which takes std::FILE *公開了擴展。

basic_filebuf(FILE *fp, char_type *buf = 0, 
       streamsize n = /* default size */); 

Constructs an object of class basic_filebuf , initializing the base class with basic_streambuf<charT,traits>() . It then calls open(fp, buf, n) .

你應該使用這是如下的方式......

FILE *pf = ...; /* e.g. fopen("/etc/passwd", "r") */ 
std::filebuf buf(pf); 
std::istream stream(&buf); 

現在,如果這種擴展是不可用,那麼恐怕沒有太多可以做其他的不是嘗試實施您自己的std::streambuf,實現所需的工作。

+0

我試圖用你的代碼的第二部分,但我得到的錯誤: 文件:對於調用「的std :: basic_filebuf :: basic_filebuf(FILE *)」 -----代碼沒有匹配功能* fp = fopen(「./ Output_BinaryImage.pgm」,「r」); std :: filebuf buf(fp); std :: istream流(&buf); – inblueswithu

+0

@inblueswithu完全讀我的帖子 - 我解決了這個錯誤,它是'std :: filebuf'的一個非標準擴展 – oldrinb

5

一般而言,您可以將而不是轉換爲FILE*std::ifstream。然而,這並不是真的有必要:創建一個自定義流緩衝區可以用來初始化一個std::istream是合理的直接。使用std::istream應該足夠了,因爲std::ifstream提供的額外功能無論如何都不能真正幫助解析。只要你不需要使用seek,創建一個用於從FILE*讀取的流緩衝區就非常簡單。只需要重寫的std::streambuf::underflow()功能:

class stdiobuf 
    : std::streambuf 
{ 
private: 
    FILE* d_file; 
    char d_buffer[8192]; 
public: 
    stdiobuf(FILE* file): d_file(file) {} 
    ~stdiobuf() { if (this->d_file) fclose(this->d_file); } 
    int underflow() { 
     if (this->gptr() == this->egptr() && this->d_file) { 
      size_t size = fread(this->d_file, 8192); 
      this->setg(this->d_buffer, this->d_buffer, this->d_buffer + size); 
     } 
     return this->gptr() == this->egptr() 
      ? traits_type::eof() 
      : traits_type::to_int_type(*this->gptr()); 
    } 
}; 

所有剩下的就是初始化一個std::istream使用stdiobuf

stdiobuf  sbuf(fopen(...)); 
std::istream in(&sbuf); 

我剛纔輸入上面的代碼,目前我不能試試看。然而,基本的內容應該是正確的,儘管可能有類型,甚至可能有一些缺陷。

+1

這需要一個小修改第三個參數'size'在this-> setg()應該是'this-> d_buffer + size' –

+0

@BostonWalker:fixed。謝謝! –