/********************************
第七题:
在根"/"目录下,'.'的设备号与索引节点号是相同的,".."也是如此.利用这个信息编写 pwd 程序.
程序必须从寻找当前目录开始,寻找当前目录名是通过读取父目录的内容来实现的.程序然后根据文件系统的层次继续寻找父目录的父目录,直到程序到达根目录.
向后(从当前目录一直到根目录)输出目录名很容易.你的 pwd 程序如何以正确的方法输出目录名(从根目录到当前目录)?
********************************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
char *myname;
int process();
int main(int argc, char **argv)
{
int errs = 0;
myname = argv[0];
errs += process();
printf("\n");
return (errs != 0);
}
int process( void )
{
struct stat statb;
ino_t cur_inode;
ino_t inode;
DIR *dir;
struct dirent *direntp;
char buf[BUFSIZ];
if ( stat(".", &statb) == -1 )
{
fprintf(stderr, "%s: Cannot stat file: %s\n", myname, strerror(errno) );
exit(1);
}
inode = statb.st_ino;
if ( stat("..", &statb) == -1 )
{
fprintf(stderr, "%s: Cannot stat file: %s\n", myname, strerror(errno) );
exit(1);
}
cur_inode = statb.st_ino;
if( cur_inode != inode )
{
chdir("..");
if( (dir = opendir(".")) == NULL ){
fprintf(stderr, "%s: Cannot open directory\n", myname, strerror(errno) );
exit(1);
}
while( (direntp = readdir( dir )) != NULL )
if( direntp->d_ino == inode )
{
strcpy(buf, direntp->d_name);
closedir( dir );
}
if ( stat(".", &statb) == -1 )
{
fprintf(stderr, "%s: Cannot stat file: %s\n", myname, strerror(errno) );
exit(1);
}
process();
printf("/%s", buf);
}
return 0;
}