加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 10:06:40 所属栏目:百科 来源:网络整理
导读:我对realpath函数有一个奇怪的问题.当函数被赋予一个作为程序参数接收的字符串时,该函数会起作用,但是当给出我在源代码中定义的字符串时,该函数会失败.这是一个简单的程序: #include stdlib.h#include limits.h#include stdio.hint main(int argc,const cha
我对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("Failedn");
    }
    else
    {
        printf("%sn",fullpath);
    }
}

当我使用参数?/ Desktop / 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);
    }
}

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

Failed

为什么第二个失败?

解决方法

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

在您的程序中,波形符(即:?)未被展开(e.i:替换为主目录的路径).

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读