该程序模拟系统的 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;
}
* 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;
}