C++ c++;将文件连接返回到成员,以便同一类的其他方法可以使用
我来自PHP。在PHP中,我们可以将文件处理程序返回到变量:C++ c++;将文件连接返回到成员,以便同一类的其他方法可以使用,c++,file,oop,file-io,singleton,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)
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
}
只需使用可以通过引用传递的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
//...
}
用法(在int main或类似版本中):
通过这种方式,您可以传递原始的filestream
对象,以便对该文件执行任何操作。还要注意的是,如果只想使用输入文件流,可以将函数专门化为std::ifstream
,反之,可以使用std::ofstream
输出文件流
参考资料:
std::fstream filestream;
std::string filename;
handle_file(filestream, filename);