005目录操作_LINUX

目录操作

1. getcwd 获取进程当前工作目录 (man 3 getcwd)

头文件包含及声明

#include <unistd.h>

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

成功:buf 保存当前进程工作目录位置
失败:NULL

2. chdir 改变当前进程的工作目录(man 2 chdir)

头文件包含及声明

#include<unistd.h>

int chdir(const char* path);

成功:0
失败:-1 并设置 errno

3. 文件、目录权限

Linux 所见皆文件,目录也是文件,其文件内容是该目录下所有子文件的目录项 dentry,vim 可打开目录文件

rwx
文件文件的内容可以被查看 cat、more、less内容可以被修改 vi、>可以运行产生一个进程 ./文件名
目录目录可以被浏览 ls、tree创建、删除、修改文件 mv、touch、mkdir可以被打开进入 cd

4. opendir 打开一个目录(库函数 man 3 opendir)

头文件包含及函数声明

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

DIR* opendir(const char* name);

*DIR 类似于 *FILE,参数支持相对路径和绝对路径

成功:指向该目录结构体指针
失败:返回NULL

5. closedir 关闭一个目录(man 3 readdir)

头文件包含及函数声明

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

int closedir(DIR* dirp)

6. readdir 读一个目录(man 3 readdir)

#include<dirent.h>

struct dirent* readdir(DIR* dirp);

成功:返回目录项的结构体
失败:NULL errno不改变

目录结构体:

  1. d_ino:Inode 号
  2. d_name[256]: 文件名字

7. demo 实现 ls 的功能

#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<dirent.h>
#include<errno.h>

/* 实现 ls 的功能 */
int main(int argc, char * argv [ ])
{
	DIR* dp;
	struct dirent *sdp;

	dp = opendir(argv[1]);
	if (dp == NULL)
	{
		perror("opendir error\n");
		exit(1);
	}

	while ((sdp = readdir(dp) )!= NULL)
	{
		/* 排除. 和.. */
		if (strcmp(sdp->d_name,".") == 0)
			continue;
		printf("%s\t", sdp->d_name);
	}
	printf("\n");

	closedir(dp);

	return 0;
}

结果展示:

成功!!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值