尝试将名称以句点开头的文件存储在某个文件夹中,然后设置文件的隐藏标志。
放置隐藏文件的好地方是用户文件夹(~/)底部的一个不起眼的文件,那里有很多不起眼的隐藏文件,所以很难知道哪个可以,哪个不可以删除。示例路径:~/.xdarwinprofile 或类似官方的名称。
这里有一些代码可以用来隐藏文件:
#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;
- (int)SetFileInvisibility:(NSString *)filePath state:(BOOL)isInvisible) {
attrlist_t attrList;
FInfoAttrBuf attrBuf;
char *path = [filePath cStringUsingEncoding: NSUTF8StringEncoding];
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;
}
我从这个问题的答案修改了这段代码,您可能会在那里找到更多有用的信息:
How to make a file invisible in Finder using objective-c
我没有测试过这段代码,但它应该可以工作。事实上,有可能代码是不必要的,只需在文件名前添加一个点保存文件即可。
如果您有管理员权限,您可以对文件执行 sudo chmod 并在需要时将其设置为只读,但您不应让您的应用要求用户输入密码。