linux 下c语言的pwd 实现

20155211实现mypwd

关于pwd

在Linux层次结构中,用户可以在被授权的任意目录下利用mkdir命令创建新目录,也可以利用cd命令从一个目录转换到另一个目录。然而,没有提示符来告知用户目前处于哪一个目录中。想要知道当前所处的目录,可以用pwd命令,该命令显示整个路径名。

  • -L
    如果 PWD 环境变量包含了不包含文件名 .(点)或 ..(点点)的当前目录的绝对路径名,则显示 PWD 环境变量的值。否则,-L 标志与 -P 标志一样运行。
  • -P
    显示当前目录的绝对路径名。与 -P 标志一起显示的绝对路径不包含在路径名的绝对路径中涉及到符号链接类型的文件的名称。
    退出状态
  • 该命令返回以下出口值:
    0 成功完成。 >0 发生错误。

pwd实现

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include    <pwd.h>
ino_t get_inode(char *);
void printpathto(ino_t);
void inum_to_name(ino_t, char *, int);

int main() {
 printpathto(get_inode(".")); /* print path to here */
 putchar('\n'); /* then add newline */
 return 0;
}

/*
 *        prints path leading down to an object with this inode
 * kind of recursive
 */
void printpathto(ino_t this_inode) {
 ino_t my_inode;
 char its_name[BUFSIZ];
 if (get_inode("..") != this_inode) {
  chdir(".."); /* up one dir */
  inum_to_name(this_inode, its_name, BUFSIZ);/* get its name*/
  my_inode = get_inode("."); /* print head */
  printpathto(my_inode); /* recursively */
  printf("/%s", its_name); /* now print name of this */
 }
}
void inum_to_name(ino_t inode_to_find, char *namebuf, int buflen) {
 DIR *dir_ptr; /* the directory */
 struct dirent *direntp; /* each entry  */
 dir_ptr = opendir(".");
 if (dir_ptr == NULL) {
  perror(".");
  exit(1);
 }/* search directory for a file with specified inum */
 while ((direntp = readdir(dir_ptr)) != NULL)
  if (direntp->d_ino == inode_to_find) {
   strncpy(namebuf, direntp->d_name, buflen);
   namebuf[buflen - 1] = '\0'; /* just in case */
   closedir(dir_ptr);
   return;
  }
 fprintf(stderr, "error looking for inum %d\n", inode_to_find);
 exit(1);

}

/*
 * returns inode number of the file
 */
ino_t get_inode(char *fname) {
 struct stat info;

 if (stat(fname, &info) == -1) {
  fprintf(stderr, "Cannot stat ");
  perror(fname);
  return 1;
 }
 return info.st_ino;
}

posted on   20155211  阅读(266)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示