c - 如何正确打印文件路径?

标签 c linux shell pwd

尝试为 c shell 创建密码。这是我在网站上找到的,想了解更多。 我已经在整个程序中一直使用调试 printf 语句,它返回“。”而不是实际的目录名称。我错过了什么?为什么会这样?

#include <dirent.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main()
{
    struct stat stat_buf;   
    struct dirent *file_info;
    ino_t itself_ino;       /* holds current folder inode */
    ino_t parent_ino;       /* holds parent folder inode */
    char Current[PATH_MAX];  /* folder name */
    char Path[PATH_MAX];     /* holds the full path */
    char Slash[PATH_MAX];    /* add / before the folder name */ 
    DIR *dir;

    while (1)
    {   
        dir = opendir(".");
        if(dir == NULL) { 
            fprintf(stderr, "cannot get current directory.\n");
            exit(-1);
        }
        /* read the information about the current folder */
        file_info = readdir(dir);

        lstat(file_info->d_name, &stat_buf);
        itself_ino = stat_buf.st_ino;
        closedir(dir);

        chdir("..");    /* go to parent directory */
        dir = opendir(".");

        file_info = readdir(dir);
        lstat(file_info->d_name, &stat_buf);
        parent_ino = stat_buf.st_ino;

        if(itself_ino == parent_ino) {
            /*closedir(dir);*/
            break;
        } else {
            strcpy(Slash, "/");
            strcpy(Current, file_info->d_name);
            strcat(Slash, Current);  /* add "/" as the first */ 
            strcat(Slash, Path);     /* charcter of the directory */ 

            /* check the length of the pathname */
            if(strlen(Slash)  >= PATH_MAX) {
                fprintf(stderr, "Error! Path too long!\n");
                exit(0);
            }           
            /* save the full pathname */       
            strcpy(Path, Slash);
        }
        closedir(dir);
    }

    /* print the full path of the current working directory */
    printf("%s\n", Path);
    return 0;
}

最佳答案

就是realpath :

if (realpath(".", &Path) == NULL) {
   // handle error
}

然而,也许您的目标是 getcwdget_current_dir_name

printf("%s\n", get_current_dir_name());

关于c - 如何正确打印文件路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53402194/

相关文章:

linux - gnome-打开窗口定位

linux - Bash- Count Newlines 通过终端命令

c++ - GCC对尖括号的实现包括。为什么必须如下所述?

c - 我应该使用 "-ansi"还是显式 "-std=..."作为编译器标志?

c++ - linux 上的链接问题(找不到合适的库的名称)

c++ - CMake - 不同目标的不同包含目录?

c - 释放变量后,我们可以使用它吗?

c - 如何使用 Avro C 库解码从 Kafka 读取的二进制文件?

linux - 如何将以下日期更改为 2 个特定表格? (Linux 终端/shell )

bash - 如何评估变量 bash 脚本中的变量?