سؤال

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.

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

There's no issue with calling stat with a relative path name. Not quite sure what you mean by 'negative results', it'd be worth checking the actual error returned and checking that you have (for instance) permissions to examine the file in question

All components of the path must exist and be traversable as-is at the time that stat is called. That means, for example, that this would work:

stat("direxists/../file_exists", &stat_struct);

while this would not:

stat("dirnotexist/../file_exists", &stat_struct);

even though dirnotexist/../file_exists could be normalized to yield ./file_exists. The second call will yield an ENOENT error. See here for more details: https://linux.die.net/man/2/stat

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top