C++中判断某一文件或目录是否存在
方法1. C++中较简单方法(使用文件流打开文件)
#include <iostream>
#include <fstream>
using namespace std;
#define FILENAME "*.dat" // 指定文件名
int main( void )
{
fstream _file;
_file.open(FILENAME, ios::in);
if(!_file)
{
cout<<FILENAME<<"没有被创建!"<<endl;
}
else
{
cout<<FILENAME<<"已经存在!"<<endl;
}
cin.get();
return 0;
}
方法2. 利用C语言库函数(_access)
函数原型:
int _access( const char *path, int mode )
函数参数:
path:文件路径。
mode:读写属性。
返回值(MSDN):
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.
EINVAL Invalid parameter.
函数功能(MSDN):
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.
/* ACCESS.C: This example uses _access to check the
* file named "ACCESS.C" to see if it exists and if
* writing is allowed.
*/
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
void main( void )
{
/* Check for existence */
if( (_access( "ACCESS.C", 0 )) != -1 )
{
printf( "File ACCESS.C exists " );
/* Check for write permission */
if( (_access( "ACCESS.C", 2 )) != -1 )
printf( "File ACCESS.C has write permission " );
}
}
输出:
>>File ACCESS.C exists.
>>File ACCESS.C has write permission
方法3. 使用Windows API函数FindFirstFile(...)
(1) 检查某一文件是否存在:
#include "windows.h"
int main(int argc, char *argv[])
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
printf ("Target file is %s. ", argv[1]);
hFind = FindFirstFile(argv[1], &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
printf ("Invalid File Handle. Get Last Error reports %d ", GetLastError ());
}
else
{
printf ("The first file found is %s ", FindFileData.cFileName);
FindClose(hFind);
}
return 0;
}
(2) 检查某一目录是否存在:
// 目录是否存在的检查:
BOOL CheckFolderExist(const string &strPath)
{
WIN32_FIND_DATA FindFileData;
BOOL bValue = false;
HANDLE hFind = FindFirstFile(strPath.c_str(), &FindFileData);
if ((hFind != INVALID_HANDLE_VALUE) && (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
bValue = TRUE;
}
FindClose(hFind);
return bValue;
}
方法4. 使用boost库中filesystem类库的exists函数
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/convenience.hpp>
using namespace boost::filesystem;
int GetFilePath(std::string &strFilePath)
{
string strPath;
int nRes = 0;
//指定路径
strPath = "C:\";
path full_path( initial_path() );
full_path = system_complete( path(strPath, native ) );
//判断各级子目录是否存在,不存在则需要创建
if ( !exists( full_path ) )
{
bool bRet = create_directories(full_path);
if (false == bRet)
{
return -1;
}
}
strFilePath = full_path.native_directory_string();
return 0;
}