Linux系统目录操作的系统调用


一、目录操作函数

1. mkdir库函数

在指定路径下创建一个目录,参数mode指定了该目录的权限。如果目标目录已经存在,则报错File exists。创建成功返回0,如果失败则返回-1.

下面是mkdir库函数需要引入的头文件与函数声明。

#include <sys/stat.h>
#include <sys/types.h>

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

2. rmdir库函数

删除指定路径下的目录。删除成功返回0,否则返回-1.

下面是rmdir库函数需要引入的头文件与函数声明。

#include <unistd.h>

int rmdir(const char *pathname);

3. rename库函数

#include <stdio.h>

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

4.chdir库函数

改变当前进程的工作目录。成功返回0,否则返回-1.

#include <unistd.h>

int chdir(const char *path);

5. getcwd库函数

获取当前进程的工作目录,返回值与buf均为当前工作目录路径的字符串。

#include <unistd.h>

char *getcwd(char *buf, size_t size);

6.示例程序

在part06目录下创建了c程序文件,获取当前目录后并打印后,更改工作目录为在父目录下的目录part07,并在新的工作目录中创建test.txt文件。

#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
int main()
{
    char buf[64];
    getcwd(buf, sizeof(buf));
    printf("当前工作目录:%s\n", buf);
    
    int ret = chdir("../part07");
    if(ret == -1){
        perror("chdir");
        return -1;
    }
    getcwd(buf, sizeof(buf));
    printf("修改后的工作目录:%s\n", buf);
    ret = open("test.txt", O_CREAT | O_RDWR, 0664);
    if(ret == -1){
        perror("open");
        return -1;
    }
    return 0;
}

二、目录遍历函数

1. opendir库函数

返回一个指向该目录下第一个文件的文件结构体指针。如果文件不能被打开或是打开失败,返回NULL。

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

DIR *opendir(const char *name);

2.readdir库函数

返回下一个文件的指针。失败或是到达当前目录结尾,返回NULL。

#include <dirent.h>

struct dirent *readdir(DIR *dirp);

3. closedir库函数

关闭打开的文件目录。

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

int closedir(DIR *dirp);

4. 示例程序

下面的程序实现了在终端给出目标文件夹路径,输出目标文件夹下普通文件(非文件夹)的个数

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

int fileNumCount(char* path);
int main(int argc, char* argv[])
{
    if(argc == 1){
        printf("参数数量不足!\n");
        return -1;
    }
    
    int ans = fileNumCount(argv[1]);
    printf("%s 目录下普通文件个数:%d\n", argv[1], ans);

    return 0;
}

int fileNumCount(char* path){
    DIR* dirp = opendir(path);
    int ans = 0;
    struct dirent* p = readdir(dirp);
    while(p){
        if(p == NULL)
            break;
        if(strcmp(p->d_name, ".") == 0 || strcmp(p->d_name, "..") == 0){
            ;
        }
        //文件夹
        else if(p->d_type == DT_DIR){
            char* newPath = strcat(path, "/");
            newPath = strcat(newPath, p->d_name);
            ans += fileNumCount(newPath);
        }
        //普通文件
        else{
            ans++;
        }
        p = readdir(dirp);
    }
    closedir(dirp);
    return ans;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值