Linux目录操作函数

一、chdir函数:修改当前进程的路径 <unistd.h>,修改此函数所在进程的可执行程序的历经
int chdir(const char*path);

./a.out ../test/.  改变./a.out 进程所在的路径

二、getcwd函数:获取当前进程的工作路径
getcwd(buf, sizeof(buf));

三、mkdir函数 int mkdir(const char*str, mode_t mode); 此函数创建的目录需要给执行权限,否则打不开

四、rmdir函数:删除一个空目录
int rmdir(const char*pathname);

属于man第三章
五、opendir函数:打开一个目录
DIR *opendir(const char *name);
DIR *fopendir(int fd);

DIR结构指针,内部结构体,保存所打开目录的信息

六、readdir:读目录
struct dirent *readdir(DIR *ddirp); //返回一个记录文件信息的结构体

****opendir和readdir应用——递归读取目录中文件个数

Linux目录结构就是树状结构,遍历目录需用到递归

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>

int getFileNum(char *path)
{
    // open dirent
    DIR *dir = NULL;
    dir = opendir(path);
    if(dir == NULL)
    {
        perror("opendir");
        exit(1);
    }
    
    //遍历当前打开目录
    struct dirent *ptr = NULL;
    char tmpPath[1024] = {0};
    int total = 0;
    while((ptr = readdir(dir)) != NULL)
    {
        //过滤 . 和 ..
        if(strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0)
        {
            continue;
        }
        
        if(ptr->d_type == DT_DIR)
        {
            //递归读目录
            sprintf(tmpPath, "%s/%s", path, ptr->d_name);
            total += getFileNum(tmpPath);
        }
        
        //如果是普通文件
        if(ptr->d_type == DT_REG)
        {
            total++;
        }
    }
    
    closedir(dir);  //获取完毕必须关闭目录,否则获取不到数目
    return total;
}

int main(int argc, char **argv)
{
    if(argc < 2)
    {
        printf("./a.out dir\n");
        exit(1);
    }
    
    int total = getFileNum(argv[1]);
    printf("%s has file numbers: %d\n", argv[1], total);
    
    return 0;
}


七、文件描述符的复制(重定向)
dup和dup2函数:用来复制文件描述符
<unistd.h>

描述符复制:新分配一个文件描述符使得两个文件描述符指向同一个文件

int dup(int oldfd); //返回文件描述符中未被使用的最小的描述符
int dup2(int olddup, int newfd);


1、old——》new:如果new是一个被打开的文件描述符,再拷贝前先关闭new
2、old和new对应同一个文件描述符,不会关闭new,直接返回old


fcntl:改变已经打开文件的属性,在文件打开时,不许关闭文件属性就可以改变文件读写权限
现阶段学会:获得/设置文件状态标记
int fcntl(int fd, int cmd,long arg); 
arg:一般为0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Star星屹程序设计

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

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

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

打赏作者

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

抵扣说明:

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

余额充值