linux -> C/C++ 目录操作

15 篇文章 0 订阅

创建/删除目录

#include<sys/stat.h>
int mkdir(const char *path_name,mode_t mode);
#include<unistd.h>
int rmdir(const char *path_name);

rmdir要求删除的目录为空目录,当目录非空时会操作失败

目录文件的打开/关闭/读取

#include<dirent.h>
DIR *opendir(const char *path_name);  //打开目录
int closedir(DIR *dp);   //关闭目录
struct dirent *readdir(DIR *dp); //读取目录

读取目录的示例代码

#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <time.h>
int main()
{
    struct stat statbuf;
    DIR *dir=opendir("testdir");
    dirent* dip;
    while ((dip = readdir(dir))!=NULL)
    {   
        lstat(dip->d_name, &statbuf);
        printf("%s , %s\n", dip->d_name,   ctime(&statbuf.st_atime));
    }
    return 0;
}

当前工作路径

#include<unistd.h>
int chdir(const char *path_name);   //切换工作路径
int fchdir(int fd);  //切换工作路径
char * getcwd(char*buf,size_t size);  //获取当前目录路径(绝对路径)

示例代码

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
int main()
{
    int res = chdir("testdir");
    if (res==-1)
    {
        printf("cd dir falid!");
    }
    else
    {
        char npath[200];        
        getcwd(npath,200);
        printf("%s\n", npath);
    }
    return 0;
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值