寫入程序, 需要在文件夾中寫入數據, 如果文件夾不存在, 則無法寫入, 在程序入口需要判斷;
由於屬於系統層, 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;
}