Write your own shell command pwd

Source: Internet
Author: User
Tags lstat

Thinking: (1) get "." The I node number, called N (using stat)

(2) ChDir. (using ChDir)

(3) Find the node with inode number n and get its file name.

Repeat the above operation until the current folder "." The inode value equals "..." The Inode value

#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h>ino_t get_ Inode (char *), void Printpathto (ino_t), void Inum_to_name (ino_t, char *,int), int main () {Printpathto (Get_inode (".")); printf ("\ n"); return 0;} ino_t Get_inode (char * filename) {struct stat buffer;if (lstat (filename,&buffer) = =-1) {perror ("can ' t stat"); exit (1) ;} return Buffer.st_ino;} void Printpathto (ino_t ino) {ino_t ino_parent = Get_inode (".."); if (ino_parent = = Ino) return;else{struct stat S;char buffer[255];chdir (".."); Inum_to_name (ino,buffer,255);p Rintpathto (ino_parent);p rintf ("/%s", buffer);}}  void Inum_to_name (ino_t Ino,char * buffer,int buffer_length) {DIR * dir;struct dirent * direntp;struct stat Stat_buffer;dir = Opendir ("."); if (dir = = NULL) {perror ("can ' t open dir."); Exit (1);} while (direntp = Readdir (dir)) = NULL) {lstat (Direntp->d_name,&stat_buffer); if (Stat_buffer.st_ino = = Ino) { strncpy (buffer,direntp->d_name,buffer_length); buffer[buffer_length-1] = ' + '; Closedir (dir); return;}} 


Write your own shell command pwd

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.