标签:图片 rcp stat int 记录 sys stdio.h std include
题目要求
学习pwd命令
2.研究pwd实现需要的系统调用(man -k; grep),写出伪代码
man-k directory | grep 2
{
getinode(".");获取当前目录节点
getinode(".."); 获取父目录节点
记录当前节点的目录名;
只有当inode == up_inode时,打印。
}
3.实现pwd命令
代码
#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);
}
标签:图片 rcp stat int 记录 sys stdio.h std include
原文地址:https://www.cnblogs.com/heyanda/p/10017909.html