2013-10-23 48 views
0

我來自PHP。在PHP中,我們可以返回文件句柄到一個變量:C++返回文件連接到一個成員,所以可以被同一類的其他方法使用

class FileHandler 
    { 
     private $_fileHandler; 

     public function __construct() 
     { 
       $this->_fileHandler = fopen('log.txt', 'a'); 
     } 

     public function writeToFile($sentence) 
     { 
       fwrite($this->_fileHandler, $sentence); 
     } 
    } 

我現在面臨的問題是,在C時,我希望它分配給成員,所以我可以通過我的課++中使用它給錯誤

FileUtils::FileUtils() 
    { 
    // I do not what type of variable to create to assign it 
    string handler = std::ofstream out("readme.txt",std::ios::app); //throws error. 
    // I need it to be returned to member so I do not have to open the file in every other method 
    } 

回答

2

只需使用一個FileStream對象,可以通過引用傳遞:

void handle_file(std::fstream &filestream, const std::string& filename) { 
    filestream.open(filename.c_str(), std::ios::in);//you can change the mode depending on what you want to do 
    //do other things to the file - i.e. input/output 
    //... 
} 

USAGE(在INT主或類似的):

std::fstream filestream; 
std::string filename; 

handle_file(filestream, filename); 

這樣,你可以通過原來的filestream對象來做任何你喜歡的文件。另外請注意,如果您只想使用輸入文件流,則可以將您的功能專用於std::ifstream,反之用std::ofstream輸出文件流。

參考:

http://www.cplusplus.com/doc/tutorial/files/

http://en.cppreference.com/w/cpp/io/basic_ifstream

http://en.cppreference.com/w/cpp/io/basic_ofstream

相關問題