forked from viewfinderco/viewfinder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileUtils.ios.mm
97 lines (89 loc) · 2.59 KB
/
FileUtils.ios.mm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// Copyright 2012 Viewfinder. All rights reserved.
// Author: Peter Mattis.
#import <dirent.h>
#import <errno.h>
#import <fcntl.h>
#import <sys/stat.h>
#import <sys/xattr.h>
#import <unistd.h>
#import "FileUtils.h"
#import "Logging.h"
void FileExcludeFromBackup(const string& path, bool is_dir) {
if (kIOSVersion == "5.0.1") {
const char* name = "com.apple.MobileBackup";
uint8_t value = 1;
if (setxattr(path.c_str(), name, &value, sizeof(value), 0, 0) != 0) {
LOG("setxattr failed: %s: %d (%s)", path, errno, strerror(errno));
}
} else if (kIOSVersion >= "5.1") {
NSURL* url = [NSURL fileURLWithPath:NewNSString(path) isDirectory:is_dir];
NSError* error = NULL;
if (![url setResourceValue:[NSNumber numberWithBool: YES]
forKey:NSURLIsExcludedFromBackupKey
error:&error]) {
LOG("exclude from backup failed: %s: %s", path, error);
}
}
}
void DirExcludeFromBackup(const string& path, bool recursive) {
if (recursive) {
DIR* dir = opendir(path.c_str());
if (!dir) {
return;
}
struct dirent* r = NULL;
while ((r = readdir(dir)) != 0) {
const string name(r->d_name, r->d_namlen);
if (name == "." || name == "..") {
continue;
}
const string subpath(path + "/" + name);
struct stat s;
if (lstat(subpath.c_str(), &s) < 0) {
continue;
}
if (s.st_mode & S_IFDIR) {
DirExcludeFromBackup(subpath, true);
} else {
FileExcludeFromBackup(subpath);
}
}
closedir(dir);
}
FileExcludeFromBackup(path, true);
}
bool WriteDataToFile(const string& path, NSData* data,
bool exclude_from_backup) {
return WriteStringToFile(
path, Slice((const char*)data.bytes, data.length),
exclude_from_backup);
}
NSData* ReadFileToData(const string& path) {
int fd = open(path.c_str(), O_RDONLY);
if (fd < 0) {
// LOG("open failed: %s: %d (%s)", path, errno, strerror(errno));
return NULL;
}
struct stat s;
if (fstat(fd, &s) < 0) {
LOG("stat failed: %s: %d (%s)", path, errno, strerror(errno));
return NULL;
}
int n = s.st_size;
char* p = reinterpret_cast<char*>(malloc(n));
NSData* data = [[NSData alloc] initWithBytesNoCopy:p
length:n
freeWhenDone:YES];
while (n > 0) {
ssize_t res = read(fd, p, n);
if (res < 0) {
LOG("read failed: %s: %d (%s)", path, errno, strerror(errno));
data = NULL;
break;
}
p += res;
n -= res;
}
close(fd);
return data;
}