本站首页    管理页面    写新日志    退出


«September 2025»
123456
78910111213
14151617181920
21222324252627
282930


公告

戒除浮躁,读好书,交益友


我的分类(专题)

日志更新

最新评论

留言板

链接

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;}


阅读全文(13332) | 回复(0) | 编辑 | 精华
 



发表评论:
昵称:
密码:
主页:
标题:
验证码:  (不区分大小写,请仔细填写,输错需重写评论内容!)



站点首页 | 联系我们 | 博客注册 | 博客登陆

Sponsored By W3CHINA
W3CHINA Blog 0.8 Processed in 0.049 second(s), page refreshed 144778183 times.
《全国人大常委会关于维护互联网安全的决定》  《计算机信息网络国际联网安全保护管理办法》
苏ICP备05006046号