方法一:C++中比较简单的一种办法(使用文件流打开文件)
1 #include <iostream> 2 #include <fstream> 3 4 using namespace std; 5 6 #define FILENAME "*.dat" // 指定文件名 7 8 int main( void ) 9 { 10 fstream _file; 11 _file.open(FILENAME, ios::in); 12 if(!_file) 13 { 14 cout<<FILENAME<<"没有被创建!"<<endl; 15 } 16 else 17 { 18 cout<<FILENAME<<"已经存在!"<<endl; 19 } 20 21 cin.get(); 22 return 0; 23 }
方法二:利用C语言库函数(_access)
函数原型:
int _access( const char *path, int mode )
函数参数:
l path:文件路径
l 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
方法三:使用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; }
方法四:使用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; }