|
C/C++中判斷某一文件或目錄是否存在
1.C++很簡單的一種辦法:
#include <iostream>
#include <fstream> using namespace std; #define FILENAME "stat.dat" int main() { fstream _file; _file.open(FILENAME,ios::in); if(!_file) { cout<<FILENAME<<"沒有被創(chuàng)建"; } else { cout<<FILENAME<<"已經(jīng)存在"; } return 0; }
2.利用 c 語言的庫的辦法:
函數(shù)名: access 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 Example
3.在windows平臺下用API函數(shù)FindFirstFile(...): (1)檢查文件是否存在: #define _WIN32_WINNT 0x0400
#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 wfd; bool rValue = false; HANDLE hFind = FindFirstFile(strPath.c_str(), &wfd); if ((hFind != INVALID_HANDLE_VALUE) && (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { rValue = true; |
|
|