pwd 命令编写

该程序模拟系统的 pwd命令,当然功能也没有它的强大

程序主要是使用 chdir(const char* path)函数,该函数使当前的目录跳转到指定的目录中

程序使用递归的方式一步一步的返回目录的路径

相关函数介绍 成功返回0,失败返回-1

mkdir(char *pathname,mode_t mode)

rmdir(const char* path)

unlink(const char *path)

link(const char *old,const char *new)

rename(const char* from,const char *to) 重命名函数实际是先建立与新文件的连接,然后删除以前的连接来实现文件重命名的,使用link,unlink函数

 

/* *
* pwd.c
*/
#include
< stdio.h >
#include
< unistd.h >
#include
< sys / types.h >
#include
< sys / stat.h >
#include
< dirent.h >
void  print_cur_path();
void  get_path_name( int  ino, char   * path_name);
int  get_ino( char   * dir_name);
int  main( int  ac, char   * av[])
{
print_cur_path(get_ino(
" . " ));
printf(
" \n " );
return   0 ;
}
void  print_cur_path( int  ino)
{
char  path_name[BUFSIZ];
        
if (get_ino( " .. " ) != ino)
        {
                chdir(
" .. " );
                get_path_name(ino,path_name);
                print_cur_path(get_ino(
" . " ));
                printf(
" /%s " ,path_name);
        }
}
void  get_path_name( int  ino, char   * path_name)
{
        DIR 
* dir;
        
struct  dirent  * dir_name = NULL;

        
if ((dir = opendir( " . " )) == NULL)
        {
                perror(
" can'n open current directory.\n " );
                exit(
1 );
        }
        
while ((dir_name = readdir(dir)) != NULL)
        {
                
if (dir_name -> d_ino == ino)
                {
                strncpy(path_name,dir_name
-> d_name,BUFSIZ);
                path_name[BUFSIZ
- 1 ] = ' \0 ' ;
                closedir(dir);
                
return ;
                }
        }
        perror(
" read directory name error.\n " );
        error(
1 );
        closedir(dir);

}
int  get_ino( char   * dir_name)
{
struct  stat st_file;
if (stat(dir_name, & st_file) ==- 1 )
        {
        perror(dir_name);
        exit(
1 );
        }
return  st_file.st_ino;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值