Using stat() to determine file permissions

I'm having a problem verifying a directory's permissions using the stat() command. I want to flag an error condition if the directory is WRITABLE by either group or other. This is the code I'm using:

if (stat(dirname,&statbuf) == -1) {
fprintf(stderr,"Unable to run stat() command\n");
exit(1);
}

if ((statbuf.st_mode & S_IWGRP == S_IWGRP) || (statbuf.st_mode & S_IWOTH = S_IWOTH)) {
fprintf(stderr, "Directory % should only be writable by the owner\n", dirname);
exit(1);
}

This code is behaving quite strangely for me. The error line is getting printed when the directory is EXECUTABLE by group or other. I've looked in stat.h and I'm using the correct #define macros. Can anybody spot anything wrong with this ?

I can't believe you even got that to compile. statbuf.st_mode & S_IWOTH is not an l-value. Please tell me that the = in the if statement is really an == which would at least be legal.

Look at your subexpression:
(statbuf.st_mode & S_IWGRP == S_IWGRP)

First you are asking the compiler if S_IWGRP is equal to S_IWGRP. It is, so that becomes a 1. Next you are doing a bitwise "and" of 1 and statbuf.st_mode. So the whole subexpression is asking if the last bit of statbuf.st_mode is on.

You need to use:
((statbuf.st_mode & S_IWGRP) == S_IWGRP)
to get the effect that you want.

Thanks. I knew it was something stupid. I hardly ever use the bitwise operators so that's why I was confused. It makes sense now too because the execute bit was the one that was causing the expression to be TRUE. That is the last bit in that entire bit mask. Thanks again.

Yes, it was "==". That was a typo.