linux学习之路(四)

目录操作相关的函数

1.文件重命名

int rename(const char* oldpath,const char*newpath);

2.修改当前进程(应用程序)的路径

int chdir(const char*path);
参数:切换的路径

#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>

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

    int ret = chdir(argv[1]);
    if(ret == -1)
    {
        perror("chdir");
        exit(1);
    }

    int 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;
}

在这里插入图片描述
3.获取当前进程的工作目录

char getcwd(charbuf,size_t size);
返回值:

成功:当前的工作目录
失败:NULL

参数:

buf:缓冲区,存储当前的工作目录
size:缓冲区的大小

4.创建目录mkdir

int mkdir(const char* pathname,mode_t mode);
参数:

pathname:创建的目录名
mode:目录权限、八进制的数、实际权限:mode&~umask

5.删除一个空目录
int rmdir(const char * pathname)’
参数:空目录的名字

目录遍历函数介绍

1.打开一个目录

DIR *opendir(const char *name);

参数:目录名
返回值:指向目录的指针

2.读目录

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 未知

struct dirent *readdir(DIR *dirp);
参数:opendir的返回值
返回值:目录项结构体

3.关闭目录

int closedir(DIR *dirp);

#读取指定目录下普通文件的个数

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>

int get_file_count(char* root)
{
    DIR* dir;
    struct dirent* ptr = NULL;
    int total = 0;
    char path[1024];

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

    while((ptr = readdir(dir)) != NULL)
    {
        if(strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0)
        {
            continue;
        }
        if(ptr->d_type == DT_DIR)
        {
            sprintf(path, "%s/%s", root, ptr->d_name);
            total += get_file_count(path);
        }
        if(ptr->d_type == DT_REG)
        {
            total ++;
        }
    }
    closedir(dir);

    return total;
}

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

    int total = get_file_count(argv[1]);
    printf("%s has %d files!\n", argv[1], total);

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值