gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:04:52 24 4
gpt4 key购买 nike

我在使用 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";

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

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

关于C realpath 函数不适用于源文件中定义的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44311220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com