码迷,mamicode.com
首页 > 系统相关 > 详细

linux文件操作篇 (四) 目录操作

时间:2019-03-31 19:18:09      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:指针   linu   puts   属性   lin   stat   path   include   建立   

#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
//创建文件夹 路径 掩码 
int mkdir(const char *path, mode_t mode);
// 获取当前工作路径 buf用于接受路径缓存 char *getcwd(char *buf, size_t size);
// 进入文件夹 和cd一样 int chdir(const char *path); //打开路径并建立子目录流,返回子目录流指针 DIR *opendir(const char *filename);
//读取子目录流结构 struct dirent *readdir(DIR *dirp);
//函数返回值里记录着子目录流的当前位置 long telldir(DIR *dirp);
//对dir指定的子目录流中的目录数据项的指针进行设置,loc的值用来设置指针位置,他应该通过telldir调用获得。 void seekdir(DIR *dirp, long loc);
//关闭子目录流 int closedir(DIR *dirp);

 

dirent 结构体之一

 struct dirent{             /* when _DARWIN_FEATURE_64_BIT_INODE is NOT defined */
  ino_t d_ino;                   /* file number of entry */
  __uint16_t d_reclen;             /* length of this record */
  __uint8_t d_type;                /* file type, see below */
  __uint8_t d_namlen;              /* length of string in d_name */
  char d_name[255+1];          /* name must be no longer than this */
};

 

举个例子

>> dir.c << 

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>

void scan_dir(const char *dir, int depth)
{

    DIR *dp;
    struct dirent *entry;
    struct stat statbuff;

    if(dir == NULL)
    {
        puts("please in put dir_path");
        return;
    }

    dp = opendir(dir);
    if(dp == NULL)
    {
        puts("cant open this dir");
        return;
    }

    chdir(dir); //    切换到目标文件夹

    while((entry = readdir(dp)) != NULL){

        lstat(entry->d_name,&statbuff); //获取文件属性
        
        if(statbuff.st_mode & S_IFDIR)    //判断是否是文件夹,如果是文件夹,就使用递归函数
        {
            if( strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name,"..") == 0)
            {
                continue;
            }
            printf(">%*s%s/\n",depth,"", entry->d_name);
            //scan_dir(entry->d_name,depth+4);

        }else{                            //如果不是文件夹,就直接输出文件名
            printf("%*s%s\n",depth, "",entry->d_name );
        }

    }
        chdir("..");
        closedir(dp);

}

 

>> dir.h <<

 

>> main.c <<

 

2.4 删除目录或文件操作

#include <unistd.h>
//删除文件夹
intrmdir(constchar*path);
//删除文件
intunlink(constchar*path);

linux文件操作篇 (四) 目录操作

标签:指针   linu   puts   属性   lin   stat   path   include   建立   

原文地址:https://www.cnblogs.com/kmist/p/10632512.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!