c – 更改或检查std :: ofstream的openmode
发布时间:2020-12-16 07:33:38 所属栏目:百科 来源:网络整理
导读:在一些使用std :: ofstream执行大量文件i / o的代码中,我正在缓存流以提高效率.但是,有时我需要更改文件的openmode(例如append vs truncate).这是一些类似的模拟代码: class Logger {public: void write(const std::string str,std::ios_base::openmode mod
在一些使用std :: ofstream执行大量文件i / o的代码中,我正在缓存流以提高效率.但是,有时我需要更改文件的openmode(例如append vs truncate).这是一些类似的模拟代码:
class Logger { public: void write(const std::string& str,std::ios_base::openmode mode) { if (!myStream.is_open) myStream.open(path.c_str(),mode); /* Want: if (myStream.mode != mode) { myStream.close(); myStream.open(path.c_str(),mode); } */ myStream << str; } private: std::ofstream myStream; std::string path = "/foo/bar/baz"; } 有谁知道: >有一种方法可以改变ofstream的开放模式吗? 解决方法
@Ari由于默认实现不允许你想要的东西,你可能必须封装ofstream并提供额外的get / set开放模式功能,在这个功能中你的新对象将模拟所需的行为.
也许是这样的 class FileOutput{ private: ostream& streamOut; std::ios_base::openmode currentOpemMode; public: FileOutput(ostream& out,std::ios_base::openmode mode) : streamOut(out),currentOpemMode(mode){} void setOpenMode(const std::ios_base::openmode newOpenMode){ if(newOpenMode != currentOpemMode){ currentOpemMode = newOpenMode; updateUsedMode(); } } private: void updateUsedMode(){ if(currentOpemMode == ios_base::app){ /* use seekg/tellg to move pointer to end of file */} else if(currentOpenMode == binary){ /* close stream and reopen in binary mode*/} //...and so on }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |