Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

linux

realpath

I'm having a weird problem with the realpath function. The function works when it is given a string received as an argument for the program, but fails when given a string that I define in the source code. Here is a simple program:

#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);
    }
}

When I run this with an argument ~/Desktop/file (file exists and is a regular file) I get the expected output

/home/<username>/Desktop/file

Here is another version of the program:

#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);
    }
}

When I run this program I get the output

Failed

Why does the second one fails?

like image 321
Jona Avatar asked Feb 04 '23 08:02

Jona


2 Answers

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

the tilde character (i.e.: ~) is not being expanded (e.i.: replaced with the path of your home directory) in your program.

When you provide it as an argument in the command line as in your first program, it is expanded by the shell.

like image 133
ネロク・ゴ Avatar answered Feb 06 '23 21:02

ネロク・ゴ


The shell is expanding the ~ to the correct name before you run the program and that's what is in argv[1].

When hardcoded, it obviously is not autoexpanding the name for you.

like image 28
lostbard Avatar answered Feb 06 '23 20:02

lostbard