C realpath function does not work for lines defined in source file

I am having a strange problem with a function realpath

. The function works when given a string given as an argument to the program, but fails when given a string that I define in the source code. Here's 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 it with an argument ~/Desktop/file

( file

exists and is a regular file) I get the expected output

/home/<username>/Desktop/file

      

Here's 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 doesn't the second one work?

+3


source to share


2 answers


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

      

the tilde character (i.e.:) is ~

not expanded (e.g. replaced with your home directory path) in your program.



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

+6


source


The shell expands ~ to the correct name before running the program and whatever is in argv [1].



In case of hard coding, it clearly doesn't auto-expand the name for you.

+1


source







All Articles