【问题标题】:C realpath function doesn't work for strings defined in the source fileC realpath 函数不适用于源文件中定义的字符串
【发布时间】:2017-06-01 15:08:43
【问题描述】:

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/filefile 存在并且是一个常规文件)运行它时,我得到了预期的输出

/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

为什么第二个失败了?

【问题讨论】:

  • 与你的问题无关,但你为什么要动态分配fullpath?为什么不是数组?
  • 至于你的问题,你有没有试过把argv[1]打印出来看看是什么?并在通话失败时检查errno?我还建议您阅读the realpath manual page

标签: c linux realpath


【解决方案1】:
const char* path = "~/Desktop/file";

波浪字符(即:~)没有被扩展(即:替换为您的主目录的路径)在你的程序中。

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-28
      相关资源
      最近更新 更多