linux系统目录操作

1 chdir 函数。修改当前进程的路径
头文件unistd.h
函数原型:int chdir(const char *path);
函数说明:chdir()用来将当前的工作目录改变成以参数path 所指的目录.
2 getcwd 函数
获取当前进程工作目录
函数原型:char *getcwd(char *buf, size_t size);
size就是给定的buf的size。
案例:

int main(int argc, char*argv[])
{
        int fd;
        int ret;
        if(argc<2)
        {
                printf("need file.\n");
                exit(1);
        }
        ret = chdir(argv[1]);//输入一个目录,修改当前进程的路径
        if(ret == -1)
        {
                perror("chdir.\n");
                exit(1);
        }
        fd = open("chdir.txt",O_CREAT|O_RDWR,0777);//新创建一个文件
        if(fd == -1)
        {
                perror("open");
                exit(1);
        }
        close(fd);
        char buf[128];
        getcwd(buf,sizeof(buf));//获取当前进程的执行目录
        printf("current dir:%s\n",buf);
        return 0;
}

执行:./chdir  ../

3 mkdir 函数
作用:创建目录
注意:创建的目录需要有执行权限,否则无法进入目录
函数原型
int mkdir(const char *pathname, mode_t mode);
4 rmdir 函数
作用:删除一个空目录
函数原型:int rmdir(const char *pathname);

5 opendir 函数
作用:打开一个目录
函数原型:DIR *opendir(const char *name);
返回值
DIR结构指针,该结构是一个内部结构,保存所打开的目录信息,作用类似于FILE结构
函数出错返回 NULL
头文件:sys/types.h dirent.h
6 readdir 函数
作用:读目录
函数原型:struct dirent *readdir(DIR *dirp);
返回值:返回一条记录项
struct dirent
{
ino_t d_ino; // 此目录进入点的inode
ff_t d_off; // 目录文件开头至此目录进入点的位移
signed short int d_reclen; // d_name 的长度, 不包含NULL 字符
unsigned char d_type; // d_name 所指的文件类型
har d_name[256]; // 文件名
};
d_type
DT_BLK - 块设备
DT_CHR - 字符设备
DT_DIR - 目录
DT_LNK - 软连接
DT_FIFO - 管道
DT_REG - 普通文件
DT_SOCK - 套接字
DT_UNKNOWN - 未知
-D_BSD_SOURCE 编译时添加宏定义

7 closedir 函数
作用:关闭目录
案例:递归读目录,统计文件数

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

    int getFileNum(char *path)
    {
    DIR *dir = NULL;
    struct dirent *ptr=NULL;
    char buf[1024]={0};
    int total=0;
    dir = opendir(path);//打开一个目录

    if(dir == NULL)
    {
           perror("opendir");
           exit(1);
    }

    while((ptr = readdir(dir)) != NULL)
    {
            //过滤掉. 和 .. 目录
           if(strcmp(ptr->d_name,".")==0 || stccmp(ptr->d_name,"..")==0)
                   continue;
            //如果是目录进入递归
           if(ptr->d_type==DT_DIR)
           {
                   sprintf(buf,"%s/%s",path,ptr->name);
                   total += getFileNum(buf);
           }
            //如果是文件则++
           if(ptr->d_type==DT_REG)
                   total++;
    }

    closedir(dir);//如果不关闭目录会发现返回值为0
    return total;
    }


    int main(int argc ,char *argv[])
    {
        if(argc <2)
        {
            printf("need a path.\n");
            exit(0);
        }


        int total =getFileNum(argv[1]);
        printf("total = %d",total);
        return 0;
    }       
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值