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