« | September 2025 | » | 日 | 一 | 二 | 三 | 四 | 五 | 六 | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | | | | | |
| 公告 |
戒除浮躁,读好书,交益友 |
Blog信息 |
blog名称:邢红瑞的blog 日志总数:523 评论数量:1142 留言数量:0 访问次数:9709161 建立时间:2004年12月20日 |

| |
[c++]c语言c++判断目录和文件是否存在 原创空间, 软件技术, 电脑与网络
邢红瑞 发表于 2007/9/8 17:50:06 |
windows平台下使用vc或gcc函数名: 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就行了。linux下或者gcc下#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 指针类似,它是一个用于跟踪目录流的操作系统特定的对象。使用c++标准库#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"即可使用Windows API PathFileExists
#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前面定义使用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;} |
|
|