关于C++中如何判断文件,目录存在的若干方法

在我们平时的编程时,经常需要判断文件 或者 目录是否存在,相对来说判断文件的存在性比较简单,目录则比较复杂。

 

下面就详细的介绍几种方法。

首先关于判断文件的存在性:

1. 使用c++或C中提供的关于文件操作的一些方法。

在C++中,可以利用ifstream文件输入流,当我们直接使用ifstream来创建文件输入流的时候,如果文件不存在则流创建失败。

 

ifstream fin("hello.txt"); if (!fin) { std::cout << "can not open this file" << endl;

 这是c++中最常用的方式。

c中也是同样道理,我们可是File的相关操作。

File* fh = fopen("hello","r"); if(fh == NULL) { printf("%s","can not open the file"); }

 

当然C中还有一种方式是直接调用c的函数库。

就是函数 int _access(const char* path,int mode);

这个函数的功能十分强大。

可以看看msdn的详细介绍

#include <io.h> #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" ); } }

这三种方式算是判断文件存在比较简单快捷的方法了。

现在来说说判断目录存在的一些方法。

在C++中可以调用系统的一些函数

WIN32_FIND_DATA wfd; 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);

 

但这种方法稍微显得复杂一些。

现在介绍一个轻量级的方法

在windows中可以使用_stat() 函数。

声明:int _stat(const char* path, struct _stat* buffer);

这个函数使用起来非常方便,如下:

struct _stat fileStat; if ((_stat(dir.c_str(), &fileStat) == 0) && (fileStat.st_mode & _S_IFDIR)) { isExist = true; }

_S_IFDIR 是一个标志位,如果是目录的话,该位就会被系统设置。

 

在linux底下也有相对应的函数stat();

使用方法基本相同:

 

struct stat fileStat; if ((stat(dir.c_str(), &fileStat) == 0) && S_ISDIR(fileStat.st_mode)) { isExist = true; }

唯一不同的地方我使用了一个macro, S_ISDIR来判断文件是否存在,原理实际都一样的。

上面就是自己使用过的几种判断文件和目录存在性的一些经验了,希望对大家有所帮助。

你可能感兴趣的:(C++,struct,File,buffer,Access,Path)