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