[英]C programming: How to get directory name?
我正在編寫代碼,以使用遞歸函數打印出從根到當前目錄或引用目錄的路徑。 但我無法獲取目錄名稱,只能獲取..在基本情況下發生問題,並調用dirent->name
。
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
static void list_dir (const char * dir_name)
{
DIR * d;
struct dirent *e;
struct stat sb;
struct stat sb2;
long childIno;
long parentIno;
char parent[200];
stat(dir_name, &sb);
if (stat(dir_name, &sb) == -1) {
perror("stat");
exit(EXIT_FAILURE);
}
childIno = (long) sb.st_ino;
/* get parent dir name */
snprintf(parent, sizeof(parent), "%s/..", dir_name);
d = opendir(parent);
stat(parent, &sb2);
if (stat(parent, &sb2) == -1) {
perror("stat2");
printf("parent name: \n");
exit(EXIT_FAILURE);
}
parentIno = (long) sb2.st_ino;
if (d == NULL) {
printf("Cannot open dircetory '%s'\n", parent);
}
/*below code is really messed up*/
if (childIno == parentIno) {
while ((e = readdir(d)) != NULL) {
printf("base case %s\n", e->d_name);
break;
}
}else{
list_dir(parent);
}
/*code above here is really messed up*/
/* After going through all the entries, close the directory. */
closedir (d);
}
int main (int argc, char** argv)
{
list_dir (argv[1]);
return 0;
}
正確的結果應該是在鍵入命令行時
./pathto .
應該打印出從根目錄到我當前目錄的路徑
或者如果命令行這樣
./pathto file.txt
應該打印出從根目錄到file.txt的路徑
可以使用<dirent.h>
和stat
進行此操作,但確實很棘手。 POSIX為此提供了一個稱為realpath
的功能。 省略錯誤檢查:
#include <limits.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char buf[PATH_MAX];
puts(realpath(argv[1], buf));
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.