c++将文件连接返回给成员,因此可以由同一类的其他方法使用

标签 c++ file oop file-io singleton

我来自 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
  }

最佳答案

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

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

关于c++将文件连接返回给成员,因此可以由同一类的其他方法使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19530566/

相关文章:

java - 派生类可以调用它们的抽象父类的构造函数,调用它们尚未实现的方法吗?

c++ - 如何在 C++ 中创建自定义的 logic_error 派生类?

c++ - 如何使用 gtest 运行部分测试用例

python - 如何从映射文件中读取行?

python-3.x - 将新创建的文件夹的名称放在 csv 文件的路径中

python - 占位符类方法 Python 3

C++ 成员函数多态性问题

java - ISO C++ 禁止声明没有类型的 'init' [-fpermissive]

c++ - 有没有办法让vim在另一个终端窗口中运行 “make”命令?

c++ - 将数据实时写入文件或在程序关闭时写入文件更好吗?