0

我来自 PHP。在 PHP 中,我们可以将文件处理程序返回给一个变量:

    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
  }
4

1 回答 1

2

只需使用文件流对象,您可以通过引用传递:

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
    //...
}

用法(在 int main 或类似中):

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

于 2013-10-23T01:19:31.183 回答