Linux系统下mybash中pwd和ls命令的实现

Linux系统下mybash中pwd和ls命令的实现

1、pwd的实现:
调用getcwd函数来实现

#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>

int main()
{
	char dir_buff[512] = {0};
	getcwd(dir_buff,512);
	printf("%s\n",dir_buff);
	exut(0);
}

2、ls命令的实现
ls的实现先调用函数getcwd获得当前目录,打开目录流opendir,读取目录流中的信息。关闭目录流。

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<dirent.h>
#include<sys/type.h>

int main()
{
	char dir_buff[512] = {0};
	getcwd(dir_buff,512);//获取当前目录
	DIR *p = opendir(dir_buff);//打开目录流
	if(p == NULL)
	{
		perror("opendir err");
		exit(1);
	}
	struct dirent *s = NULL;
	//读取目录流中的信息,每条信息(struct dirent)对应一个文件
	while((s = readdir(p)) != NULL)
	{
		if(strncmp (s->d_name,".",1)!=0)
			printf("%s   ",s->d_name);//打印文件名
	}
	printf("\n");
	closedir(p);//关闭目录流
	exit(0);
}

程序运行截图:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值