您的位置:首页 > 编程语言 > C语言/C++

C/C++中判断某一文件或目录是否存在

2015-07-08 16:12 495 查看


C/C++中判断某一文件或目录是否存在

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<<"没有被创建";

}

else

{

cout<<FILENAME<<"已经存在";

}

return 0;

}

2.利用 c 语言的库的办法:
函数名: access

功 能: 确定文件的访问权限

用 法: int access(const char *filename, int amode);

以前一直没用过这个函数,今天调试程序发现了这个函数,感觉挺好用,尤其是判断一个文件或文件夹是否存在的时候,用不着再find了,文件的话还可以检测读写权限,文件夹的话则只能判断是否存在,下面摘自MSDN:

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

00 Existence only

02 Write permission

04 Read permission

06 Read and write permission

Example
/* 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 " );
}
}
[/code]
Output[/code]
File ACCESS.C existsFile ACCESS.C has write permission


3.在windows平台下用API函数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;

}

FindClose(hFind);

return rValue;

}

4.使用boost的filesystem类库的exists函数

#include <boost/filesystem/operations.hpp>

#include <boost/filesystem/path.hpp>

#include <boost/filesystem/convenience.hpp>

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;

}

=================


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

在我们平时的编程时,经常需要判断文件或者目录是否存在,相对来说判断文件的存在性比较简单,目录则比较复杂。
下面就详细的介绍几种方法。

首先关于判断文件的存在性:
一、ifstream
在C++中,可以利用ifstream文件输入流,当我们直接使用ifstream来创建文件输入流的时候,如果文件不存在则流创建失败。

ifstream fin("hello.txt");

if (!fin)

{

std::cout << "can not open this file" << endl;

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

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

File* fh = fopen("hello","r");

if(fh == NULL)

{

printf("%s","can not open the file");

}

三、_access
当然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" );

}

}

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

现在来说说判断目录存在的一些方法。
一、FindFirstFile
在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);

二、_stat()
现在介绍一个轻量级的方法
在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++ 检查文件是否存在 百度
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: