C++遍历文件夹及判断某一文件或目录是否存在

2024-02-06 05:32

本文主要是介绍C++遍历文件夹及判断某一文件或目录是否存在,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

C++遍历文件夹的代码如下:                    

Cpp代码   收藏代码
  1. #include<iostream>     
  2. #include<string>     
  3. #include<io.h>    
  4. using namespace std;   
  5.   
  6. void   visit(string path,int layer)     
  7. {     
  8.         struct _finddata_t   filefind;     
  9.         string  curr=path+"\\*.*";     
  10.         int   done=0,i,handle;     
  11.         if((handle=_findfirst(curr.c_str(),&filefind))==-1)return;       
  12.         while(!(done=_findnext(handle,&filefind)))     
  13.         {         
  14.             printf("%s\n",filefind.name);      
  15.             if(!strcmp(filefind.name,"..")){  
  16.  continue;  
  17.             }  
  18.             for(i=0;i<layer;i++)cout<<"     ";                   
  19.             if((_A_SUBDIR==filefind.attrib)) //是目录  
  20.                 {             
  21.     printf("----------%s\n",filefind.name);      
  22.                   cout<<filefind.name<<"(dir)"<<endl;     
  23.                   curr=path+"\\"+filefind.name;     
  24.  }     
  25.            else//不是目录,是文件       
  26.               {     
  27.                         cout<<path+"\\"+filefind.name<<endl;    
  28.              }     
  29.         }             
  30.         _findclose(handle);                 
  31. }     
  32. int   main()     
  33. {             
  34.         string   path;   
  35.         cout<<"请输入目录"<<endl;     
  36.         cin>>path;  
  37.         visit(path,1);     
  38.         system("PAUSE");     
  39.         return   0;       
  40. }     

 



一、判断文件夹是否存在:
     1.用CreateDirectory(".//FileManege",NULL);如果文件夹FileManege不存在,则创建。
     2.或者if(_access(".//FileManege",0)==-1),表示FileManege不存在。
     3.或者BOOL PathIsDirectory(LPCTSTR pszPath);

二、判断文件是否存在:
     1.用if((file=fopen(".//FileManege//F//F.dat","rb"))==NULL)
         file=fopen(".//FileManege//F//F.dat","ab+"); // 先判断有无文件,没的话新建一个
     2.用if(_access(".//FileManege//F//F.dat",0)==-1),表示文件不存在。


       函数int _access( const char *path, int mode );可以判断文件或者文件夹的mode属性
       mode=00;//Existence only
       mode=02;//Write permission
       mode=04;//Read permission
       mode=06;//Read and write permission
       需要包含头文件<io.h>。





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 " );} }
Output
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++遍历文件夹及判断某一文件或目录是否存在的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/683264

相关文章

linux如何复制文件夹并重命名

《linux如何复制文件夹并重命名》在Linux系统中,复制文件夹并重命名可以通过使用“cp”和“mv”命令来实现,使用“cp-r”命令可以递归复制整个文件夹及其子文件夹和文件,而使用“mv”命令可以... 目录linux复制文件夹并重命名我们需要使用“cp”命令来复制文件夹我们还可以结合使用“mv”命令总

Python重命名文件并移动到对应文件夹

《Python重命名文件并移动到对应文件夹》在日常的文件管理和处理过程中,我们可能会遇到需要将文件整理到不同文件夹中的需求,下面我们就来看看如何使用Python实现重命名文件并移动到对应文件夹吧... 目录检查并删除空文件夹1. 基本需求2. 实现代码解析3. 代码解释4. 代码执行结果5. 总结方法补充在

C++一个数组赋值给另一个数组方式

《C++一个数组赋值给另一个数组方式》文章介绍了三种在C++中将一个数组赋值给另一个数组的方法:使用循环逐个元素赋值、使用标准库函数std::copy或std::memcpy以及使用标准库容器,每种方... 目录C++一个数组赋值给另一个数组循环遍历赋值使用标准库中的函数 std::copy 或 std::

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

Java判断多个时间段是否重合的方法小结

《Java判断多个时间段是否重合的方法小结》这篇文章主要为大家详细介绍了Java中判断多个时间段是否重合的方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录判断多个时间段是否有间隔判断时间段集合是否与某时间段重合判断多个时间段是否有间隔实体类内容public class D

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

C++初始化数组的几种常见方法(简单易懂)

《C++初始化数组的几种常见方法(简单易懂)》本文介绍了C++中数组的初始化方法,包括一维数组和二维数组的初始化,以及用new动态初始化数组,在C++11及以上版本中,还提供了使用std::array... 目录1、初始化一维数组1.1、使用列表初始化(推荐方式)1.2、初始化部分列表1.3、使用std::

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没

c++中std::placeholders的使用方法

《c++中std::placeholders的使用方法》std::placeholders是C++标准库中的一个工具,用于在函数对象绑定时创建占位符,本文就来详细的介绍一下,具有一定的参考价值,感兴... 目录1. 基本概念2. 使用场景3. 示例示例 1:部分参数绑定示例 2:参数重排序4. 注意事项5.