Search code examples
c++relative-pathstat

can we use stat with relative path to a file in c++


Can we use the stat with a relative path to the file, for checking that the file exists or not? When I used this, I am always getting negative results.


Solution

  • This code shows r=0 as output:

    #include <iostream>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <unistd.h>
    
    
    int main()
    {
        struct stat buf;
        int r = stat("../junk", &buf);
        std::cout << "r=" << r << std::endl;
    }
    

    Output from ls -l .. (cut down to show only relevant directory):

    $ ls -l ../
    drwxr-xr-x  6 username group  12288 Aug 27 09:48 junk