3

I would like to be able to hide/un-hide a file in Windows in C++, but I was concerned about erasing other attributes (like FILE_ATTRIBUTE_READONLY, FILE_ATTRIBUTE_ARCHIVE, ...).

Here is the current code:

//Hiding the file
SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN);

// Un-Hiding the file
SetFileAttributes(path, FILE_ATTRIBUTE_NORMAL);

This works fine for regular files, but will hiding the file remove a READONLY flag for example? Will unhiding the file remove it?

If yes, I was planning on doing something like this:

//Hiding the file
int attr = GetFileAttributes(path);
if ((attr | FILE_ATTRIBUTE_HIDDEN) == 0) {
    SetFileAttributes(path, attr & FILE_ATTRIBUTE_HIDDEN);
}

//Unhiding the file
int attr = GetFileAttributes(path);
if ((attr | FILE_ATTRIBUTE_HIDDEN) == FILE_ATTRIBUTE_HIDDEN) {
    SetFileAttributes(path, attr & FILE_ATTRIBUTE_HIDDEN);
}

Would that work?

nbarraille
  • 9,926
  • 14
  • 65
  • 92
  • 2
    One minor thing: don't forget to check `GetFileAttributes` return value (check whether it equals `INVALID_FILE_ATTRIBUTES`). – Bojan Komazec Apr 30 '12 at 16:47

2 Answers2

9

This test won't work, it will always be false:

if ((attr | FILE_ATTRIBUTE_HIDDEN) == 0)

It should instead say

if ((attr & FILE_ATTRIBUTE_HIDDEN) == 0)

Similarly, to test if a file is already hidden:

if ((attr & FILE_ATTRIBUTE_HIDDEN) == FILE_ATTRIBUTE_HIDDEN)

Final corrected code:

//Hiding the file
int attr = GetFileAttributes(path);
if ((attr & FILE_ATTRIBUTE_HIDDEN) == 0) {
    SetFileAttributes(path, attr | FILE_ATTRIBUTE_HIDDEN);
}

//Unhiding the file
int attr = GetFileAttributes(path);
if ((attr & FILE_ATTRIBUTE_HIDDEN) == FILE_ATTRIBUTE_HIDDEN) {
    SetFileAttributes(path, attr & ~FILE_ATTRIBUTE_HIDDEN);
}
MSalters
  • 173,980
  • 10
  • 155
  • 350
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
3

Yes, the first code will remove all other attributes.

The second code is almost correct, but you've missed ~ symbol:

// Hiding the file

int attr = GetFileAttributes(path);

if ((attr & FILE_ATTRIBUTE_HIDDEN) == 0) {
    SetFileAttributes(path, attr | FILE_ATTRIBUTE_HIDDEN);
}

// Unhiding the file

int attr = GetFileAttributes(path);

// Is it currently visible?
if ((attr & FILE_ATTRIBUTE_HIDDEN) == FILE_ATTRIBUTE_HIDDEN) {
    SetFileAttributes(path, attr & ~FILE_ATTRIBUTE_HIDDEN);
}
jnfjnjtj
  • 409
  • 4
  • 10
Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127