函数名: _access
功 能: 确定文件的访问权限
用 法: int access(const char *filename, int amode);
Determine file-access permission.
int _access( const char *path, int mode );
int _waccess( const wchar_t *path, int mode );
参考MSDN
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
Generic-Text Routine Mappings
TCHAR.H Routine | _UNICODE & _MBCS Not Defined | _MBCS Defined | _UNICODE Defined |
_taccess | _access | _access | _waccess |
Example
#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/n" );
/* Check for write permission */
if( (_access( "ACCESS.C", 2 )) != -1 )
printf( "File ACCESS.C has write permission/n" );
}
}
Output
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)检查某一目录是否存在:
4.使用boost的filesystem类库的exists函数
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 ;
}