寫入程式, 需要在檔案夾中寫入資料, 如果檔案夾不存在, 則無法寫入, 在程式入口需要判斷;
由於屬於系統層, Windows的兩種解決方案.
參考: http://stackoverflow.com/questions/8233842/how-to-check-if-directory-exist-using-c-and-winapi
1. GetFileAttributesA()函數
DWORD d = GetFileAttributesA(const char* filename); #include <windows.h>
windows系統函數, 判斷檔案夾是否存在;
代碼:
#include <iostream> #include <string> #include <windows.h> using namespace std; bool dirExists(const std::string& dirName_in) { DWORD ftyp = GetFileAttributesA(dirName_in.c_str()); if (ftyp == INVALID_FILE_ATTRIBUTES) return false; //something is wrong with your path! if (ftyp & FILE_ATTRIBUTE_DIRECTORY) return true; // this is a directory! return false; // this is not a directory! } int main(void) { std::string folder("./Test"); if (dirExists(folder)) { std::cout << "Folder : " << folder << " exist!" << std::endl; } else { std::cout << "Folder : " << folder << " doesn't exist!" << std::endl; } std::string nofolder("./TestNo"); if (dirExists(nofolder)) { std::cout << "Folder : " << nofolder << " exist!" << std::endl; } else { std::cout << "Folder : " << nofolder << " doesn't exist!" << std::endl; } return 0; }
更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/
2. _access()函數
int access(const char *filename, int mode); #include <io.h>
mode設為0, 判斷檔案是否存在; 返回0, 檔案存在;
代碼:
#include <iostream> #include <string> #include <io.h> using namespace std; bool dirExists(const std::string& dirName_in) { int ftyp = _access(dirName_in.c_str(), 0); if (0 == ftyp) return true; // this is a directory! else return false; // this is not a directory! } int main(void) { std::string folder("./Test"); if (dirExists(folder)) { std::cout << "Folder : " << folder << " exist!" << std::endl; } else { std::cout << "Folder : " << folder << " doesn't exist!" << std::endl; } std::string nofolder("./TestNo"); if (dirExists(nofolder)) { std::cout << "Folder : " << nofolder << " exist!" << std::endl; } else { std::cout << "Folder : " << nofolder << " doesn't exist!" << std::endl; } return 0; }
作者:csdn部落格 Spike_King