2017-2018-1 20155231 《信息安全系統設計基礎》實現mypwd
阿新 • • 發佈:2017-11-20
獲取文件 open 圖片 第一個 完整路徑 代碼 struct lin name
2017-2018-1 20155231 《信息安全系統設計基礎》實現mypwd
- Linux pwd命令用於顯示工作目錄。
- 執行pwd指令可立刻得知您目前所在的工作目錄的絕對路徑名稱。
- pwd命令以絕對路徑的方式顯示用戶當前工作目錄。命令將當前目錄的全路徑名稱(從根目錄)寫入標準輸出。全部目錄使用/分隔。第一個/表示根目錄,最後一個目錄是當前目錄。執行pwd命令可立刻得知您目前所在的工作目錄的絕對路徑名稱。
- pwd 命令查看默認工作目錄的完整路徑
[root@localhost ~]# pwd
/root
[root@localhost ~]#
- pwd 命令查看指定文件夾問題2解決方案:
[root@localhost ~]# cd /opt/soft/ [root@localhost soft]# pwd /opt/soft [root@localhost soft]#
實現代碼:
#include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> #include <unistd.h> #define MAX_DIR_DEPTH (256) //限制最大的目錄深度 #define TRUE 1 #define FALSE 0 //根據文件名獲取文件的inode-number ino_t get_ino_byname(char *filename) { struct stat file_stat; if(0 != stat(filename, &file_stat)) //stat()通過文件名filename獲取文件信息,並保存在buf所指的結構體stat中 { perror("stat"); exit(-1); } return file_stat.st_ino; } //根據inode-number, 在當前目錄中查找對呀的文件名 char *find_name_byino(ino_t ino) { DIR *dp = NULL; struct dirent *dptr = NULL; char *filename = NULL; if(NULL == (dp = opendir("."))) //opendir()打開一個目錄,在失敗的時候返回一個空的指針,成返回DIR結構體 { fprintf(stderr, "Can not open Current Directory\n"); exit(-1); } else { while(NULL != (dptr = readdir(dp))) //readdir()用來讀取目錄。返回是dirent結構體指針 { if(dptr->d_ino == ino) { filename = strdup(dptr->d_name); //strdup()將串拷貝到新建的位置處,返回一個指針,指向為復制字符串分配的空間;如果分配空間失敗,則返回NULL值. break; } } closedir(dp); } return filename; } int main(int argc, char *argv[]) { //記錄目名的棧 char *dir_stack[MAX_DIR_DEPTH]; unsigned current_depth = 0; while(TRUE) { ino_t current_ino = get_ino_byname("."); //通過特殊的文件名"."獲取當期目錄的inode-number ino_t parent_ino = get_ino_byname(".."); //通過特殊的文件名".."獲取當前目錄的父目錄的inode-number if(current_ino == parent_ino) break; //達到根目錄,推出循環 /*兩個inode-number不一樣*/ chdir(".."); //更改當前工作目錄,變為當前目錄的父目錄 dir_stack[current_depth++] = find_name_byino(current_ino); //"文件名"地址存放 if(current_depth >= MAX_DIR_DEPTH) //路徑名太深 { fprintf(stderr, "Directory tree is too deep.\n"); exit(-1); } } int i = current_depth - 1; for(i = current_depth - 1; i >= 0; i--) //打印路徑 { fprintf(stdout, "/%s", dir_stack[i]); } fprintf(stdout, "%s\n", current_depth == 0 ? "/" : ""); return 0; }
截圖:
2017-2018-1 20155231 《信息安全系統設計基礎》實現mypwd