加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

区分C中的文件夹和文件

发布时间:2020-12-16 03:40:48 所属栏目:百科 来源:网络整理
导读:我有这个代码打开一个目录,并检查列表是不是一个常规文件(意味着它是一个文件夹),它也将打开它.如何用C区分文件和文件夹. 如果这有帮助,这是我的代码: #include sys/stat.h#include cstdlib#include iostream#include dirent.husing namespace std;int main
我有这个代码打开一个目录,并检查列表是不是一个常规文件(意味着它是一个文件夹),它也将打开它.如何用C区分文件和文件夹.
如果这有帮助,这是我的代码:
#include <sys/stat.h>
#include <cstdlib>
#include <iostream>
#include <dirent.h>
using namespace std;

int main(int argc,char** argv) {

// Pointer to a directory
DIR *pdir = NULL;
pdir = opendir(".");

struct dirent *pent = NULL;

if(pdir == NULL){
    cout<<" pdir wasn't initialized properly!";
    exit(8);
}

while (pent = readdir(pdir)){ // While there is still something to read
    if(pent == NULL){
    cout<<" pdir wasn't initialized properly!";
    exit(8);
}

    cout<< pent->d_name << endl;
}

return 0;

}

解决方法

一种方法是:
switch (pent->d_type) {
    case DT_REG:
        // Regular file
        break;
    case DT_DIR:
        // Directory
        break;
    default:
        // Unhandled by this example
}

您可以在GNU C Library Manual上看到struct dirent文档.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读