Linux模拟实现pwd,linux下实现简易pwd命令

/*

pwd 命令

路径名通过栈存储,先入栈存储,再出栈输出

*/

#include 

#include 

#include 

#include 

#include 

#include 

#define NUM 40

/*

定义节点

*/

struct node {

char name[NUM];

struct node *pre;

};

/*

定义栈

*/

struct stack {

int num;

struct node* top;

};

/*

入栈 c1为入栈元素

*/

void push(struct stack* s1, char *c1)

{

struct node *n;

n = (struct node *)malloc(sizeof(struct node));

if (n == NULL) {

perror("malloc error");

exit(1);

}

strcpy(n->name, c1);

if (s1->num == 0)

n->pre = NULL;

else

n->pre = s1->top;

s1->num++;

s1->top =n;

}

/*

出栈 出栈元素存储在c1中

*/

void *pop(struct stack *s1, char* c1)

{

struct node *n;

if (s1->num == 0)

return NULL;

n = s1->top;

strcpy(c1, n->name);

s1->top = s1->top->pre;

s1->num--;

free(n);

}

/*

输出路径名

*/

void output(struct stack *s1)

{

char name[NUM];

while (s1->num >0) {

pop(s1, name);

/*在每个路径名前加"/",本程序只存储到根目录的下层目录,若在/home/abc下运行

栈内元素由上到下为 abc home

输出后为/home/abc

*/

printf("/%s", name);

}

printf("\n");

}

int main(void)

{

DIR *d;

struct dirent *dir;

struct stack *s1;

//node存当前节点inode, fnode存父目录inode

int node;

int fnode;

s1->num = 0;

s1->top = NULL;

if ((d = opendir(".")) == NULL )

perror("open error");

while ((dir = readdir(d)) != NULL)

if (!strcmp(".", dir->d_name)) {

node = dir->d_ino;

break;

}

closedir(d);

while (1) {

if (chdir("..") == -1) {

perror("chdir error");

exit(1);

}

if ((d = opendir(".")) == NULL) {

perror("open error");

exit(1);

}

while ((dir = readdir(d)) != NULL)

if (dir->d_ino == node) {

push(s1, dir->d_name);

break;

}

rewinddir(d);

while ((dir = readdir(d)) != NULL) {

if (!strcmp(".", dir->d_name))

node = dir->d_ino;

if (!strcmp("..", dir->d_name))

fnode = dir->d_ino;

}

if (node == fnode)

break;

closedir(d);

}

output(s1);

}

总结:

1、POSIX提供了获取当前路径的函数:

#include 

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

2、当前目录问题

例如,可执行文件放在/home/abc/123下,名为pwd

当前目录为/home/abc

此时若执行文件需要输入:123/pwd

而输出为/home/abd 而不是/home/abc/123

则当前目录为运行程序的目录,而不是文件所在位置。

3、

while ((dir = readdir(d)) != NULL)

if (dir->d_ino == node) {

push(s1, dir->d_name);

break;

}

rewinddir(d);

while ((dir = readdir(d)) != NULL) {

if (!strcmp(".", dir->d_name))

node = dir->d_ino;

if (!strcmp("..", dir->d_name))

fnode = dir->d_ino;

}

此处需要便利目录两次,开始设计算法时,将两次遍历放在了一次里面,这样导致了node参数发生变化,逻辑出现问题

浪费了大量时间

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值