2015-12-05 13:37:32|?次阅读|上传:wustguangh【已有?条评论】发表评论
关键词:C/C++, 文件操作|来源:唯设编程网
编程进行文件访问时,我们通常需要判断某个目录或者文件是否存在,本文是一些常用的c/C++判断文件/目录是否存在的方法,包括access,opendir,fstream::open,PathFileExist,exist函数,其中有的是c语言提供的函数,有的是c++的库函数,也有的是windows API函数,还包括了boost的库函数,通过例子介绍了它们的用法。供参考:
函数名: access
功 能: 确定文件的访问权限
用 法: int access(const char *filename, int amode); 文件的话还可以检测读写权限,文件夹的话则只能判断是否存在
#include "stdafx.h"
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
void main( void )
{
/* Check for exist */
if( (_access( "C:windows", 0 )) != -1 )
{
printf( "windows exists " );
}
}
其实判断文件存在fopen就行了。
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <unistd.h>
void main( void )
{
DIR *dir = NULL;
/* Open the given directory, if you can. */
dir = opendir( "C:windows" );
if( dir != NULL ) {
printf( "Error opening " );
return ;
}
}
opendir() 返回的 DIR 指针与 fopen() 返回的 FILE 指针类似,它是一个用于跟踪目录流的操作系统特定的对象。
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
#define FILENAME "C:windows"
int main()
{
fstream file;
file.open(FILENAME,ios::in);
if(!file)
{
cout<<FILENAME<<"存在";
}
else
{
cout<<FILENAME<<"不存在";
}
return 0;
}
gcc编译去掉#include "stdafx.h"即可
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <shlwapi.h>
#pragma comment(lib,"shlwapi.lib")
using namespace std;
#define FILENAME "C:windows"
int main()
{
if (::PathFileExists(FILENAME))
cout<<"exist";
return 0;
}
注意windows.h 一定要在shlwapi.h前面定义
#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:myTestTest1Test2";
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;
}
转载:http://blogger.org.cn/blog/more.asp?name=hongrui&id=28011