20155308 加分项——C语言实现Linux的pwd命令

实现要求

学习pwd命令

什么是pwd

  • pwd‘ 代表的是‘Print Working Directory’(打印当前目录)。如它的名字那样,‘pwd’会打印出当前工作目录,或简单的来说就是当前用户所位于的目录。它会打印出以根目录 (/)为起点的完整目录名(绝对目录)。

基本语法

  • pwd [OPTION]

详细用法

  • 利用man pwd查看pwd的用法

常用实例

参考

http://www.cnblogs.com/peida/archive/2012/10/24/2737730.html

学习了pwd命令

  • 实例1:用pwd命令查看默认工作目录的完整路径

  • 实例2:使用 pwd 命令查看指定文件夹

  • 实例3:/bin/pwd

命令:/bin/pwd [选项]

选项:

-L 目录连接链接时,输出连接路径

-P 输出物理路径

输出:

[root@localhost init.d]# /bin/pwd 

/etc/rc.d/init.d

[root@localhost init.d]# /bin/pwd --help

[root@localhost init.d]# /bin/pwd -P

/etc/rc.d/init.d

[root@localhost init.d]# /bin/pwd -L

/etc/init.d

研究pwd实现需要的系统调用(man -k; grep),写出伪代码

首先输入命令

man -k directory | grep 2

查看

发现getcwd()函数符合条件后,查看其用法

  • 伪代码为:
定义一个字符串数组储存绝对路径
调用函数getcwd()
if (返回的指针==NULL)
调用函数出错,发出错误报告
else
打印结果

代码实现

#include<stdio.h>
#include<sys/stat.h>
#include<dirent.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
void printpath();
char *inode_to_name(int);
int getinode(char *);
int main()
{
printpath();
putchar('\n');
return ;
}
void printpath()
{
int inode,up_inode;
char *str;
inode = getinode(".");
up_inode = getinode("..");
chdir("..");
str = inode_to_name(inode);
if(inode == up_inode) {
// printf("/%s",str);
return;
}
printpath();
printf("/%s",str);
}
int getinode(char *str)
{
struct stat st;
if(stat(str,&st) == -1){
perror(str);
exit(-1);
}
return st.st_ino;
}
char *inode_to_name(int inode)
{
char *str;
DIR *dirp;
struct dirent *dirt;
if((dirp = opendir(".")) == NULL){
perror(".");
exit(-1);
}
while((dirt = readdir(dirp)) != NULL)
{
if(dirt->d_ino == inode){
str = (char *)malloc(strlen(dirt->d_name)*sizeof(char));
strcpy(str,dirt->d_name);
return str;
}
}
perror(".");
exit(-1);

代码测试

实验感想

上课老师讲过了pwd的用法,下课我们用过这个学习,让我更好地明白了pwd的各种功能以及代码实现过程。

最新文章

  1. Taurus.MVC 2.0 开源发布:WebAPI开发教程
  2. [HTML5] Blob对象
  3. POJ 3233 Matrix Power Series 矩阵快速幂
  4. git引用^和~的区别
  5. charAt(i) 函数
  6. hdu 5640 King&#39;s Cake(模拟)
  7. CLR via C# 阅读笔记
  8. SQL Server 连接问题-命名管道
  9. GIT入门笔记(3)- git中的一些概念和原理
  10. modbus与rs485的关系_modbus与rs485的区别和联系
  11. js canvas图片压缩
  12. python基础之数据类型和数值类型
  13. java并发基础
  14. trinitycore 魔兽服务器源码分析(三) 多线程相关
  15. BZOJ4555 HEOI2016/TJOI2016求和(NTT+斯特林数)
  16. Pytorch 之 backward
  17. Linux的内存管理
  18. SSH整合:Unable to instantiate Action, employeeAction, defined for &#39;emp-list&#39; in namespace &#39;/&#39;employeeAction - action
  19. map容器结构体离散化
  20. moment.js学习总结

热门文章

  1. SQL监控:mysql及mssql数据库SQL执行过程监控审计
  2. JVM线程状态,park, wait, sleep, interrupt, yeild 对比
  3. 【OpenCV】【MFC】图片、视频、摄像头输入响应【详细图解】
  4. DateConvertUtil 日期工具类
  5. 【[HNOI2015]亚瑟王】
  6. webpack中热模块更新
  7. No.6 - 利用 CSS animation 制作一个炫酷的 Slider
  8. const引用和constexpr
  9. Linux下jmap命令查看内存使用
  10. spring学习笔记---数据库事务并发与锁详解