문제

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