1.C++很簡單的一種辦法:
2.利用 c 語言的庫的辦法:
函數名: access
功 能: 確定文件的訪問權限
用 法: int access(const char *filename, int amode);
以前一直沒用過這個函數,今天調試程序發現了這個函數,感覺挺好用,尤其是判斷一個文件或文件夾是否存在的時候,用不著再find了,文件的話還可以檢測讀寫權限,文件夾的話則只能判斷是否存在,下面摘自MSDN:
int _access( const char *path, int mode );
Return Value
Each of these functions returns 0 if the file has the given mode. The function returns –1 if the named file does not exist or is not accessible in the given mode; in this case, errno is set as follows:
EACCES
Access denied: file's permission setting does not allow specified access.
ENOENT
Filename or path not found.
Parameters
path
File or directory path
mode
Permission setting
Remarks
When used with files, the _access function determines whether the specified file exists and can be accessed as specified by the value of mode. When used with directories, _access determines only whether the specified directory exists; in Windows NT, all directories have read and write access.
mode Value Checks File For
00 Existence only
02 Write permission
04 Read permission
06 Read and write permission
Example
OutputFile ACCESS.C existsFile ACCESS.C has write permission
3.在windows平台下用API函數FindFirstFile(...):
(1)檢查文件是否存在:
(2)檢查某一目錄是否存在:
4.使用boost的filesystem類庫的exists函數
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/convenience.hpp>
int GetFilePath(std::string &strFilePath)
{
string strPath;
int nRes = 0;
//指定路徑
strPath = "D:/myTest/Test1/Test2";
namespace fs = boost::filesystem;
//路徑的可移植
fs::path full_path( fs::initial_path() );
full_path = fs::system_complete( fs::path(strPath, fs::native ) );
//判斷各級子目錄是否存在,不存在則需要創建
if ( !fs::exists( full_path ) )
{
// 創建多層子目錄
bool bRet = fs::create_directories(full_path);
if (false == bRet)
{
return -1;
}
}
strFilePath = full_path.native_directory_string();
return 0;
}