-1

i have a requirement where i need to check a given directory exists or not.

i am doing like this

structure stat buf;
stat(dir_path,buf);

if( S_ISDIR(buf.st_mode) )
cout << " its a directory " << endl;
else
cout << " its not a directory " << endl;

this procedure is not working sometimes. The output is not consistent for me.

Is it like, i should not perform S_ISDIR() when the stat() call fails ?

because what random behavior i am seeing here is..

stat() for the directory path fails and then i am trying S_ISDIR(buf.st_mode)

so, now this S_ISDIR() is not behaving correctly sometimes. why is this happening like this ? any idea ?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190

1 Answers1

3

If stat fails then the values in buf will be unspecified, won't they?

I don't see any point in examining them anyway. What possible use could the result be?

Simply don't do this if stat fails. You should always check the return value of POSIX functions.

(I'm surprised to see that the manpages don't make the behaviour clear in this case, though perhaps that's a lesson in itself.)

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • I was about to comment: "did you check stat return value?" – Jean-François Fabre Aug 20 '16 at 10:27
  • @LightnessRacesinOrbit Interestingly enough, that the [spec](http://pubs.opengroup.org/onlinepubs/009695399/functions/stat.html) doesn't tell you that `buf` is untouched (it is, simply because that's how system calls usually function) upon failure, should give pause. The contents of `buf` are indeed indeterminate after a failed call. And now I want to know, if there's little hacky program somewhere that assumes atomicity. – dhke Aug 20 '16 at 10:35
  • @dhke: I'd bet on it ;) – Lightness Races in Orbit Aug 20 '16 at 10:44