C realpath 函数不适用于源文件中定义的字符串

C realpath function doesn't work for strings defined in the source file

我在使用 realpath 函数时遇到了一个奇怪的问题。该函数在给定一个作为程序参数接收的字符串时工作,但在给定我在源代码中定义的字符串时失败。这是一个简单的程序:

#include <stdlib.h>
#include <limits.h>
#include <stdio.h>

int main(int argc, const char* argv[])
{
    char* fullpath = (char*)malloc(PATH_MAX);
    if(realpath(argv[1], fullpath) == NULL)
    {
        printf("Failed\n");
    }
    else
    {
        printf("%s\n", fullpath);
    }
}

当我 运行 这个带有参数 ~/Desktop/file 时(file 存在并且是一个常规文件)我得到了预期的输出

/home/<username>/Desktop/file

这是程序的另一个版本:

#include <stdlib.h>
#include <limits.h>
#include <stdio.h>

int main(int argc, const char* argv[])
{

    const char* path = "~/Desktop/file";

    char* fullpath = (char*)malloc(PATH_MAX);
    if(realpath(path, fullpath) == NULL)
    {
        printf("Failed\n");
    }
    else
    {
        printf("%s\n", fullpath);
    }
}

当我 运行 这个程序时,我得到输出

Failed

为什么第二个失败了?

const char* path = "~/Desktop/file";

波浪字符(即:~)未被扩展(e.i.: 替换使用程序中 主目录) 的路径。

当您像在第一个程序中一样在命令行中将其作为参数提供时,它会 由 shell 扩展。

shell 在您 运行 程序之前将 ~ 扩展为正确的名称,这就是 argv[1].

中的内容

硬编码时,显然不会为您自动扩展名称。