/*
* 文件名:mypwd.c
* 描述: 实现简单的pwd命令
*/
#include<stdio.h>
#include<stdlib.h>
#include<dirent.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
#include<unistd.h>
#define MAX_DIR_DEPTH (256)
//根据文件名获取文件inode-number
ino_t get_ino_byname(char *filename)
{
struct stat file_stat;
if (0 != stat(filename, &file_stat))
{
perror("stat");
exit(-1);
}
return file_stat.st_ino;
}
//根据inode-number,在当前目录下查找对应的文件名
char *find_name_byino(ino_t ino)
{
DIR *dp = NULL;
struct dirent *dptr = NULL;
char *filename = NULL;
if (NULL == (dp = opendir(".")))
{
fprintf(stderr,"Can not open Current Directiory\n");
exit(-1);
}
else
{
while (NULL != (dptr = readdir(dp)))
{
if (dptr->d_ino == ino)
{
filename = strdup(dptr->d_name);
break;
}
}
closedir(dp);
}
return filename;
}
int main()
{
//记录目录名的栈
char *dir_stack[MAX_DIR_DEPTH];
int current_depth = 0;
for(;;)
{
/*1.通过特殊的文件名“.”获取当前目录的inode-number*/
ino_t current_ino = get_ino_byname(".");
/*2.通过特殊的文件名“..”获取当前目录的父级目录的inode-number*/
ino_t parent_ino = get_ino_byname("..");
/*3.判断当前目录和上级目录的inode-number是否一样*/
/*4.如果两个inode-number一样说明到达根目录*/
if (current_ino == parent_ino)
{
break;
}
/*
5.如果两个inode-number不一样
切换至父级目录,根据步骤1获取的inode-number,
在父级目录中搜索对应的文件名并记录下来, 重新回到步骤1
*/
chdir("..");
dir_stack[current_depth++] = find_name_byino(current_ino);
/*输出完整路径名*/
if (current_depth >= MAX_DIR_DEPTH)
{
fprintf(stderr,"Directory tree is too deep.\n");
exit(-1);
}
}
int i = current_depth - 1;
for ( i = current_depth - 1; i >= 0; i--)
{
fprintf(stdout,"/%s",dir_stack[i]);
free(dir_stack[i]);
}
fprintf(stdout,"%s\n",current_depth == 0 ? "/":"");
return 0;
}
strdup()函数
函数和功能描述:
extern char *strdup(char *s);
头文件:string.h
功能: 将串拷贝到新建的位置处
说 明:strdup不是标准的c函数。strdup()在内部调用了malloc()为变量分配内存,不需要使用返回的字符串时,需要用free()释放相应的内存空间,否则会造成内存泄漏。
返回值:返回一个指针,指向为复制字符串分配的空间;如果分配空间失败,则返回NULL值。
/*
strdup.c
*/
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
int main()
{
char *s = "God is a girl";
char *d;
d = strdup(s);
printf("%s",d);
free(d);
return 0;
}