/*
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参数发生变化,逻辑出现问题
浪费了大量时间