File::GetAttributes Is a file read only

  • Thread starter Thread starter xenny
  • Start date Start date
X

xenny

Hi,

I'm trying to see if a file (exportfile) is set to read only using
File::GetAttributes:

if ((File::GetAttributes(exportfile.c_str()) &
FileAttributes::ReadOnly) != 0);
{
MessageBox::Show("The File is Read Only","Warning");
}

I've tried that and a few variations but it always returns true.

Any help would be greatly appreciated.

Thanks,

Chris
 
Hi,

I'm trying to see if a file (exportfile) is set to read only using
File::GetAttributes:

if ((File::GetAttributes(exportfile.c_str()) &
FileAttributes::ReadOnly) != 0);
{
MessageBox::Show("The File is Read Only","Warning");
}

I've tried that and a few variations but it always returns true.

Any help would be greatly appreciated.

You have an errant semicolon. VC warns about such "empty controlled
statements" at warning level 3 and above.
 
Doug said:
You have an errant semicolon. VC warns about such "empty controlled
statements" at warning level 3 and above.


O yeah, good point :-)

But even if I remove that it still does the same thing.

But, I've found a way to make it work:

FileAttributes fa = File::GetAttributes(exportfile.c_str());

if ((fa == ReadOnly) || (fa % 2 == 1))
{
MessageBox::Show("The File is Read Only","Warning");
}

Now that will only show the message box when the file is read only.
And will work even if the file has other attributes as well as the read
only (the second part of the if statement).

Cheers.

Chris
 
O yeah, good point :-)

But even if I remove that it still does the same thing.

But, I've found a way to make it work:

FileAttributes fa = File::GetAttributes(exportfile.c_str());

if ((fa == ReadOnly) || (fa % 2 == 1))
{
MessageBox::Show("The File is Read Only","Warning");
}

Now that will only show the message box when the file is read only.
And will work even if the file has other attributes as well as the read
only (the second part of the if statement).

That's not how to do it. The following should work:

FileAttributes attr = File::GetAttributes(exportfile.c_str());
if (attr == -1)
{
// error
}
else if (attr & FileAttributes::ReadOnly)
{
// File is readonly
}

You have to check it against -1 because that's what GetAttributes returns
in case of error, e.g. a file that doesn't exist.
 
O yeah, good point :-)

But even if I remove that it still does the same thing.

But, I've found a way to make it work:

FileAttributes fa = File::GetAttributes(exportfile.c_str());

if ((fa == ReadOnly) || (fa % 2 == 1))
{
MessageBox::Show("The File is Read Only","Warning");
}

Now that will only show the message box when the file is read only.
And will work even if the file has other attributes as well as the read
only (the second part of the if statement).

All you need is:

if (fa & ReadOnly) {
}

or

if (File::GetAttributes(exportfile.c_str()) & ReadOnly) {
}
 
Back
Top