Home > Blockchain >  C realpath return NULL vector, can't find the path
C realpath return NULL vector, can't find the path

Time:07-31

I wanted a function to return the absolute path given a relative path to an existing file. Searching online I came across realpath here: https://stackoverflow.com/a/229038/19637794 And followed the example here: Example of realpath function in C

So I wrote:

#include <limits.h>
#include <stdlib.h>
char path[PATH_MAX];

void test(void){
char *ppath = realpath("../../test/src/file", path );
if (ppath != NULL)
{
    *do stuff, read the file*
}
else
{
    return -1;
}
free(ppath);
}

int main ()
{
    test();
}

Where my working directories are as follow

dir
|---CMakeLists.txt
|---build/
|   |---test/
|       |
|       |---executable
|
|---test/
|   |---CMakeLists.txt
|   |---src/
|       |
|       |---test.c
|       |---file

I launched the executable from build directory with ./test/executable but I kept getting -1, checked with gdb and verified that ppath was 0x0.

I read My realpath return null for files But didn't seem to fit my problem

Then I read about #include <errno.h>, so added this two line and it said "No such file or directory"

else
{
    char* errStr = strerror(errno);
    printf("%s" ,errStr);
}

After that I added printf("%s", path); that returned: dir/test, which is the directory above the one I wanted, still ppath is NULL. I tried to add a file in the directory above, but doesn't seem to work either, nor with its original path nor with the new one.

I also read it might happen having realpath returning NULL if the path exceed the maximum allowed in phase of declaration, so I also tried to remove path and feeding NULL, like it was done at https://www.demo2s.com/c/c-char-real-realpath-p-null.html as follow:

char *ppath = realpath("../../test/src/file", NULL );

Which didn't work either.

What am I doing wrong?

Edit: few modify based on comment Edit2: added parenthesis between test and ;

CodePudding user response:

As your comment says "from the build directory I run ./test/executable", the present working directory is "dir/build". Starting from this directory, realpath() is right telling you that there is no "dir/build/../../test/src/file".

  • Related