zoukankan      html  css  js  c++  java
  • 2018-2019-1 20165226《信息安全系统设计基础》 pwd命令的实现

    2018-2019-1 20165226《信息安全系统设计基础》 pwd命令的实现

    一、学习pwd

    • 查看pwd

    • 得知一个嫩过去文件路径的函数——getcwd

    • i节点值

    通过ls -i -a查看...目录对应的值

    • stat结构体

    struct stat {
    mode_t st_mode; //文件对应的模式,文件,目录等
    ino_t st_ino; //inode节点号
    dev_t st_dev; //设备号码
    dev_t st_rdev; //特殊设备号码
    nlink_t st_nlink; //文件的连接数
    uid_t st_uid; //文件所有者
    gid_t st_gid; //文件所有者对应的组
    off_t st_size; //普通文件,对应的文件字节数
    time_t st_atime; //文件最后被访问的时间
    time_t st_mtime; //文件内容最后被修改的时间
    time_t st_ctime; //文件状态改变时间
    blksize_t st_blksize; //文件内容对应的块大小
    blkcnt_t st_blocks; //文件内容对应的块数量
    };

    由此可知通过ino_t返回i-Node值

    二、编写代码

    • 思路1

    (1)得到"."的i节点号,称其为n(使用stat)
    (2)chdir ..(使用chdir)
    (3)找到inode号为n的节点,得到其文件名。

    重复上述操作直到当前目录“.”的inode值等于".."的inode值

    • 代码1
    #include <stdio.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <dirent.h>
     
    ino_t get_inode(char *);
    void printpathto(ino_t);
    void inum_to_name(ino_t ,char *,int);
     
    int main()
    {
    	printpathto(get_inode("."));
    	printf("
    ");
    	return 0;
    }
     
    ino_t get_inode(char * filename)
    {
    	struct stat buffer;
    	if(lstat(filename,&buffer) == -1)
    	{
    		perror("can't stat");
    		exit(1);
    	}
    	return buffer.st_ino;
    }
     
    void printpathto(ino_t ino)
    {
    	ino_t ino_parent = get_inode("..");
    	if(ino_parent == ino)
    		return;
    	else
    	{
    		struct stat s;
    		char buffer[255];
    		chdir("..");
    		inum_to_name(ino,buffer,255);
    		printpathto(ino_parent);
    		printf("/%s",buffer);
    	}
    }
     
    void inum_to_name(ino_t ino,char * buffer,int buffer_length)
    {
    	DIR * dir;
    	struct dirent * direntp;
    	struct stat stat_buffer;
    	dir = opendir(".");
    	if(dir == NULL)
    	{
    		perror("can't open dir .");
    		exit(1);
    	}
    	while((direntp = readdir(dir)) != NULL)
    	{
    		lstat(direntp->d_name,&stat_buffer);
    		if(stat_buffer.st_ino == ino)
    		{
    			strncpy(buffer,direntp->d_name,buffer_length);
    			buffer[buffer_length-1] = '';
    			closedir(dir);
    			return;
    		}
    	}
    }
    
    • 代码2(使用getcwd)
    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    int main(){
        char *filepath=NULL;
        filepath=getcwd(NULL,0);
        puts(filepath);
        free(filepath);
        return 0;
    }
    
    • 测试结果
  • 相关阅读:
    蓝桥网试题 java 基础练习 特殊的数字
    蓝桥网试题 java 基础练习 杨辉三角形
    蓝桥网试题 java 基础练习 查找整数
    蓝桥网试题 java 基础练习 数列特征
    蓝桥网试题 java 基础练习 字母图形
    蓝桥网试题 java 基础练习 01字串
    蓝桥网试题 java 基础练习 回文数
    蓝桥网试题 java 基础练习 特殊回文数
    Using text search in Web page with Sikuli
    each of which 用法
  • 原文地址:https://www.cnblogs.com/musea/p/10014171.html
Copyright © 2011-2022 走看看