出处:http://www.cnblogs.com/project/archive/2010/12/02/1894494.html
在我们平时的编程时,经常需要判断文件或者目录是否存在,相对来说判断文件的存在性比较简单,目录则比较复杂。
下面就详细的介绍几种方法。
首先关于判断文件的存在性:
一、ifstream
在C++中,可以利用ifstream文件输入流,当我们直接使用ifstream来创建文件输入流的时候,如果文件不存在则流创建失败。
if ( ! fin)
{
std::cout << " can not open this file " << endl;
这是c++中最常用的方式。
二、File
C中也是同样道理,我们可是File的相关操作。
if (fh == NULL)
{
printf( " %s " , " can not open the file " );
}
三、_access
当然C中还有一种方式是直接调用c的函数库。
就是函数 int _access(const char* path,int mode);
这个函数的功能十分强大。
可以看看msdn的详细介绍
#include < stdio.h >
#include < stdlib.h >
int main( void )
{
// Check for existence.
if ( (_access( " crt_ACCESS.C " , 0 )) != - 1 )
{
printf_s( " File crt_ACCESS.C exists.\n " );
// Check for write permission.
// Assume file is read-only.
if ( (_access( " crt_ACCESS.C " , 2 )) == - 1 )
printf_s( " File crt_ACCESS.C does not have write permission.\n " );
}
}
这三种方式算是判断文件存在比较简单快捷的方法了。
现在来说说判断目录存在的一些方法。
一、FindFirstFile
在C++中可以调用系统的一些函数,但这种方法稍微显得复杂一些。
bool rValue = false ;
HANDLE hFind = FindFirstFile(strPath.c_str(), & wfd);
if ((hFind != INVALID_HANDLE_VALUE) && (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
std::cout << " this file exists " << endl;
}
FindClose(hFind);
二、_stat()
现在介绍一个轻量级的方法
在windows中可以使用_stat() 函数。
声明:int _stat(const char* path, struct _stat* buffer);
这个函数使用起来非常方便,如下:
if ((_stat(dir.c_str(), & fileStat) == 0 ) && (fileStat.st_mode & _S_IFDIR))
{
isExist = true ;
}
_S_IFDIR 是一个标志位,如果是目录的话,该位就会被系统设置。
在linux底下也有相对应的函数stat();
使用方法基本相同:
if ((stat(dir.c_str(), & fileStat) == 0 ) && S_ISDIR(fileStat.st_mode))
{
isExist = true ;
}
唯一不同的地方我使用了一个macro, S_ISDIR来判断文件是否存在,原理实际都一样的。
上面就是自己使用过的几种判断文件和目录存在性的一些经验了,希望对大家有所帮助。