Linux Programming Implementation PWD command
In Linux, everything is file. Directory is actually a kind of file, but this file is very special, it is stored in a corresponding table, that is, the file name and I node of the corresponding relational table, and I node is the structure of the details of the record file, such as file size, attributes, permissions, the existence of the hard disk block and so on. We create a file in a directory is to add the corresponding relationship in this table, the use of a file is based on the I node to determine the actual storage location of the hard disk. Use the "Ls-iar" command to try to look at the I node information for the file.
The kernel sets an I-node entry for each directory, that is, ".", and a portal to its parent directory I node, "..", we first get the I node number of the current directory, but do not know the name of the current directory, we switch to its parent directory, Find the name of the current I-node number. So we can easily associate the use of recursive implementation, the termination of the condition is "." and ".." The node numbers are equal.
Pseudo code:
do{opendir(".");readdir(".");printf("."->name);closedir(".");opendir("..");}while(get_inode("..") != get_inode("."))
Code:
#include <stdio.h> #include <sys/stat.h> #include <sys/types.h> #include <dirent.h> #include <stdlib.h> #include <string.h> #define SIZE 128ino_t get_inode (char *dirname); void Get_work_dir (ino_t inode _num); void Inode_to_dirname (ino_t inode_num, char *buf, int buflen); int main (void) {Get_work_dir (Get_inode (".")); printf ("\ n"); return 0;} ino_t Get_inode (char *dirname) {struct STAT info; if (stat (dirname, &info) = =-1) {perror ("dirname"); Exit (1); } return Info.st_ino;} void Get_work_dir (ino_t inode_num) {ino_t parent_inode; Char Buf[size]; if (Get_inode (".") = Inode_num) {chdir (".."); Inode_to_dirname (Inode_num, buf, SIZE); Parent_inode = Get_inode ("."); Get_work_dir (Parent_inode); printf ("/%s", buf); }}void Inode_to_dirname (ino_t inode_num, char *buf,int buflen) {DIR *dir_ptr; struct Dirent *dire; if (dir_ptr = Opendir (".")) = = NULL) {perror ("."); Exit (1); } while ((Dire = Readdir (dir_ptr)) = NULL) {if (Dire->d_ino = = Inode_num) {strncpy (bu F, Dire->d_name, Buflen); Buf[strlen (buf)] = ' n '; Closedir (DIR_PTR); return; }} fprintf (stderr, "error looking for inode number%d\n", (int) inode_num); Exit (1);}
Results:
Linux Programming Implementation PWD command