How to make a file invisible in Finder using objective-c

I need to hide the file in finder, and also in the spotlight, if possible, using objective-c or using C calls.

thanks

+4
file objective-c cocoa macos
source share
3 answers

You can set the invisibility attribute through some C calls. This is pretty crude code that only works on some file systems and lacks error checking.

#include <assert.h> #include <stdio.h> #include <stddef.h> #include <string.h> #include <sys/attr.h> #include <sys/errno.h> #include <unistd.h> #include <sys/vnode.h> typedef struct attrlist attrlist_t; struct FInfoAttrBuf { u_int32_t length; fsobj_type_t objType; union { char rawBytes[32]; struct { FileInfo info; ExtendedFileInfo extInfo; } file; struct { FolderInfo info; ExtendedFolderInfo extInfo; } folder; } finderInfo; }; typedef struct FInfoAttrBuf FInfoAttrBuf; static int SetFileInvisibility(const char *path, int isInvisible) { attrlist_t attrList; FInfoAttrBuf attrBuf; memset(&attrList, 0, sizeof(attrList)); attrList.bitmapcount = ATTR_BIT_MAP_COUNT; attrList.commonattr = ATTR_CMN_OBJTYPE | ATTR_CMN_FNDRINFO; int err = getattrlist(path, &attrList, &attrBuf, sizeof(attrBuf), 0); if (err != 0) return errno; // attrBuf.objType = (VREG | VDIR), inconsequential for invisibility UInt16 flags = CFSwapInt16BigToHost(attrBuf.finderInfo.file.info.finderFlags); if (isInvisible) flags |= kIsInvisible; else flags &= (~kIsInvisible); attrBuf.finderInfo.file.info.finderFlags = CFSwapInt16HostToBig(flags); attrList.commonattr = ATTR_CMN_FNDRINFO; err = setattrlist(path, &attrList, attrBuf.finderInfo.rawBytes, sizeof(attrBuf.finderInfo.rawBytes), 0); return err; } 

or you can go through NSURL if you can target Snow Leopard, which abstracts how each file system handles and handles extended attributes.

 NSURL *url = [NSURL fileURLWithPath:path]; [url setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsHiddenKey error:NULL]; 
+4
source share

You can use:

 chflags("/path/to/file", UF_HIDDEN); 

to hide any file.

See man chflags (2) for more details.

+6
source share

(EDIT: The leading point does not seem to support it).

Files that begin with the symbol "." will be hidden in Finder by default. Users can override this with the defaults key, but this will take care of this in general.

For a spotlight, see TA24975 for a more detailed explanation of what Lindsay mentions. You probably need to combine approaches, depending on whether you are trying to avoid mdfind -name from choosing it.

+3
source share

All Articles