dirent--文件以及文件夹相关操作(跨平台)

本文介绍了如何使用dirent库进行文件和文件夹的操作,该库在Windows和UNIX系统中都可以使用,提供了如opendir、readdir等函数。尽管在Windows上并非原生支持,但通过第三方实现的dirent.h头文件,开发者可以在Windows平台上实现类似的功能。文章还展示了如何删除文件夹内所有文件、检查路径是否存在以及判断是文件还是文件夹的例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

windows客户端开发–文件以及文件夹相关操作(windows api)
一文中,主要使用了一些windows api实现文件以及文件夹的相关操作。

c++语言本身不提供文件相关操作,我们也可以使用boost库完成我们想要的功能。

但是为了仅仅一个小功能,引入boost库,似乎有点小题大做吧,那今天就介绍一种“跨平台”的文件操作,dirent。

这里所谓的“跨平台”其实是个伪命题,不是真正意义上的。

let us go!!!

初识dirent

是POSIX.1标准定义的unix类目录操作的头文件,包含了许多UNIX系统服务的函数原型,例如opendir函数、readdir函数.

看到上面的描述,你会理解我所说的用引号引起来的“跨平台”了。

在windows平台上同样可以使用:
https://github.com/tronkko/dirent/blob/master/include/dirent.h

只是简单的包含这个头文件dirent.h就可以了,因为这个文件只有八百多行,在博客的最后面,我将会贴上这个源码。

熟悉dirent

dirent结构体:

    struct dirent {
        long d_ino;     /* Always zero */
        unsigned short d_reclen;  /* Structure size */
        size_t d_namlen;    /* Length of name without \0 */
        int d_type;   /* File type */
        char d_name[PATH_MAX];     /* File name */
    };
    typedef struct dirent dirent;

DIR:
A type representing a directory stream.

struct DIR {
        struct dirent ent;
        struct _WDIR *wdirp;
    };
    typedef struct DIR DIR;

一些函数:

int closedir(DIR *);
DIR *opendir(const char *);
struct dirent *readdir(DIR *);
int readdir_r(DIR *, struct dirent *, struct dirent **);
void rewinddir(DIR *);
void seekdir(DIR *, long int);
long int telldir(DIR *);

使用dirent

删除文件夹下所有文件:

DIR *foder = opendir(file_path_to_delete.c_str());
    struct dirent *next_file;
    char filepath[256];

    while ((next_file = readdir(foder)) != NULL)
    {
        // build the path for each file in the folder
        sprintf(filepath, "%s/%s", course_path.c_str(), next_file->d_name);
        remove(filepath);
    }

注意:
路径要以’/’结尾:

file_path_to_delete += "\/";

判断目录是否存在:

 DIR *mydir = NULL;  
    if((mydir= opendir(dir))==NULL)//判断目录   
    {  
      int ret = mkdir(dir, MODE);//创建目录  
      if (ret != 0)  
      {  
          return -1;  
      }  
      printf("%s created sucess!/n", dir);  
    }  

判断是文件夹还是文件:

unsigned char isFile =0x8;
DIR Dir;
struct dirent *DirEntry;
Dir = opendir("c:/test/")

while(Dir=readdir(Dir))
{
   if ( DirEntry->d_type == isFile)
   {
    cout <<"Found a File : " << DirEntry->d_name << endl;
   }
}

==========================================================华丽的分割线============================================================

//dirent.h

/*
* dirent.h - dirent API for Microsoft Visual Studio
*
* Copyright (C) 2006-2012 Toni Ronkko
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* ``Software''), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL TONI RONKKO BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* $Id: dirent.h,v 1.20 2014/03/19 17:52:23 tronkko Exp $
*/
#ifndef DIRENT_H
#define DIRENT_H

/*
* Define architecture flags so we don't need to include windows.h.
* Avoiding windows.h makes it simpler to use windows sockets in conjunction
* with dirent.h.
*/
#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && defined(_M_IX86)
#   define _X86_
#endif
#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && defined(_M_AMD64)
#define _AMD64_
#endif

#include <stdio.h>
#include <stdarg.h>
#include <windef.h>
#include <winbase.h>
#include <wchar.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>

/* Indicates that d_type field is available in dirent structure */
#define _DIRENT_HAVE_D_TYPE

/* Indicates that d_namlen field is available in dirent structure */
#define _DIRENT_HAVE_D_NAMLEN

/* Entries missing from MSVC 6.0 */
#if !defined(FILE_ATTRIBUTE_DEVICE)
#   define FILE_ATTRIBUTE_DEVICE 0x40
#endif

/* File type and permission flags for stat() */
#if !defined(S_IFMT)
#   define 
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一苇渡江694

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值