string getHomeFilePath(){
TCHAR fileName[256] = { 0 };
::GetModuleFileName(NULL, fileName, sizeof(fileName) / sizeof(fileName[0]));
string strTemp = fileName;
string::size_type nPos=strTemp.rfind('\\', string::npos);
strTemp.substr(0, nPos + 1);
return strTemp;
}
//使用对象管理资源
//在析构函数中吞掉异常
//确保数据的安全性 采用返回 const FILE* getFilePtr()const
class AutoFile{
public:
AutoFile(const string & fileName){
cout << "fopen" << endl;
pFile = nullptr;
errno_t err=fopen_s(&pFile, fileName.c_str(), "ab");
if (err != 0) cout << "fopen failed!" << endl;
}
~AutoFile(){
try{
if (pFile != nullptr){
cout << "fclose" << endl;
fclose(pFile);
}
}
catch (...){
OutputDebugString("AutoFile throw exception");
}
}
const FILE* getFilePtr()const{
return pFile;
}
private:
FILE *pFile;
};
#define ASIZE(arr) ( sizeof(arr)/sizeof(arr[0]) )
void wirteContent(){
string fileName = getHomeFilePath() + ".test.cc";
AutoFile autoFile(fileName);
char szCont[] = "天空之城";
fwrite(szCont, ASIZE(szCont), 1, const_cast<FILE*>(autoFile.getFilePtr()));
}
学习effective c++小感悟
最新推荐文章于 2021-01-23 10:01:22 发布