linux 下c语言的pwd 实现
2024-09-29 11:09:17
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;
}
最新文章
- Jmeter实现登录bugfree、新建bug、解决bug脚本(抓包工具实现)
- ASP.NET MVC 过滤器(四)
- 在eclipse之中使用Junit
- JAVA魔法堂:折腾Mybatis操作SQLite的SQLException:NYI异常
- Winform开发框架主界面设计展示
- JS案例之6——瀑布流布局(1)
- python解无忧公主数学题107.py
- asp 下拉框二级联动
- BZOJ3530: [Sdoi2014]数数
- 如何让虚拟目录里面的webconfig不继承网站的设置
- C#基础知识01(continue、break 和 return、ref 和 out)
- BZOJ 1708: [Usaco2007 Oct]Money奶牛的硬币
- ssm整合说明与模板-Spring Spring MVC Mybatis整合开发
- 前端页面中如何在窗口缩放时让两个div始终在同一行显示
- WebSocket和Socket
- CDH 报错:under replicated blocks
- MySQL 8.0常见问题
- Python学习之旅(八)
- entity framework 缓存干扰的数据不一致问题
- HTML中元素的position属性详解