C语言目录操作

获取当前目录

在shell中通过命令 pwd显示当前工作目录,才C中通过调用getcwd函数获取

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

getcwd函数把当前目录存入buf中,如果目录名超出了参数size,函数返回NULL,如果成功返回buf

切换工作目录

函数声明

int chdir(const char *path);

在shell中通过cd命令切换目录,返回值0表示成功,其他为失败

目录的创建和删除

在shell中天通过mkdir/rmdir来创建、删除目录,c程序中用mkdir\rmdir函数来创建删除目录

int mkdir(const char *pathname, mode_t mode)
//mode 将open系统调用的O_CREAT选项中的有关定义设置
mkdir("/test/aaa",0755);

//删除
int rmdir(const char *pathname);

获取文件列表

在实际开发中,文件是存放在目录中的,在处理文件之前,必须先知道目录中有哪些文件

1.包含头文件

#include<dirent.h>

2.相关库函数
打开目录的函数

DIR *opendir(const char *pathname)

读取目录的函数readdir

struct dirent*readdir(DIR *dirp);

关闭目录的函数

int closed(DIR *dirp);

数据结构:目录指针DIR
struct dirent:头文件封装完成,关注文件名和文件类型即可

struct dirent
{
   long d_ino;                    // inode number 索引节点号
   off_t d_off;                   // offset to this dirent 在目录文件中的偏移 
   unsigned short d_reclen;     // length of this d_name 文件名长 
   unsigned char d_type;         // the type of d_name 文件类型
   char d_name [NAME_MAX+1];    // file name文件名,最长255字符
};
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值