1. 程式人生 > >2018-2019-1 20165226《資訊安全系統設計基礎》 pwd命令的實現

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("\n");
    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] = '\0';
            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;
}
  • 測試結果