自己写Linux下的pwd命令

来源:互联网 发布:mac搜狗输入法怎么设置 编辑:程序博客网 时间:2024/05/16 07:06
pwd命令用来显示到达当前目录的路径。
/*以下代码在opensuse11下编译通过
结构体dirent保存目录的详细信息
struct dirent {
ino_t          d_ino;       /* inode number */
off_t           d_off;       /* offset to the next dirent */
unsigned   short d_reclen;    /* length of this record */
unsigned char d_type;      /* type of file */
char           d_name[256]; /* filename */
};
*/
#include <stdio.h>#include <sys/types.h>#include <sys/stat.h>#include <dirent.h>#define BUFSIZE 512ino_t get_inode(char *); //从目录名得到此目录的i-节点号void print_path(ino_t); //以递归形式打印路径void inum_to_name(ino_t, char *, int); //将i-节点号转换为对应的目录名int main(){print_path(get_inode("."));putchar('\n');return 0;}void print_path(ino_t curr_inode){ino_t my_inode;char its_name[BUFSIZE];if(get_inode("..") != curr_inode){ //比较此目录的父目录是否是本身,是的话表示到达根目录chdir(".."); //如不是 进入上级目录inum_to_name(curr_inode, its_name, BUFSIZE); my_inode = get_inode(".");print_path(my_inode);printf("/%s", its_name);}}void inum_to_name(ino_t inode_to_find, char *namebuf, int buflen){DIR *dir_ptr;struct dirent *direntp;dir_ptr = opendir(".");if(dir_ptr == NULL){perror(".");exit(1);}while((direntp = readdir(dir_ptr)) != NULL){if(direntp -> d_ino == inode_to_find){strncpy(namebuf, direntp -> d_name, buflen);namebuf[buflen-1] = '\0';closedir(dir_ptr);return;}}fprintf(stderr, "error looking for inum %d",inode_to_find);exit(1);}ino_t get_inode(char *fname){struct stat file_info;if(stat(fname, &file_info) == -1){fprintf(stderr, "Can't stat!");perror(fname);exit(1);}return file_info.st_ino;}