Progress
This commit is contained in:
@@ -157,87 +157,6 @@ int file_size(Handle fd, size_t *len)
|
||||
#endif
|
||||
}
|
||||
|
||||
// TODO: port to windows
|
||||
#ifndef _WIN32
|
||||
// TODO: test this
|
||||
static string parent_path(string path)
|
||||
{
|
||||
if (path.len > 0 && path.ptr[path.len-1] == '/')
|
||||
path.len--;
|
||||
|
||||
if (path.len == 0)
|
||||
return S("");
|
||||
|
||||
while (path.len > 0 && path.ptr[path.len-1] != '/')
|
||||
path.len--;
|
||||
|
||||
if (path.len > 0)
|
||||
path.len--;
|
||||
|
||||
return path;
|
||||
}
|
||||
static int write_bytes(int fd, string data)
|
||||
{
|
||||
size_t written = 0;
|
||||
while (written < (size_t) data.len) {
|
||||
int ret = sys_write(fd, data.ptr + written, data.len - written);
|
||||
if (ret < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
return -1;
|
||||
}
|
||||
written += (size_t) ret;
|
||||
}
|
||||
assert((size_t) data.len == written);
|
||||
return 0;
|
||||
}
|
||||
int file_write_atomic(string path, string content)
|
||||
{
|
||||
string parent = parent_path(path);
|
||||
|
||||
char pattern[] = "/tmp_XXXXXXXX";
|
||||
|
||||
char tmp_path[PATH_MAX];
|
||||
if (parent.len + strlen(pattern) >= (int) sizeof(tmp_path))
|
||||
return -1;
|
||||
memcpy(tmp_path, parent.ptr, parent.len);
|
||||
memcpy(tmp_path + parent.len, pattern, strlen(pattern));
|
||||
tmp_path[parent.len + strlen(pattern)] = '\0';
|
||||
|
||||
int fd = sys_mkstemp(tmp_path);
|
||||
if (fd < 0)
|
||||
return -1;
|
||||
|
||||
if (write_bytes(fd, content) < 0) {
|
||||
sys_close(fd);
|
||||
sys_remove(tmp_path);
|
||||
return -1;
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
if (sys__commit(fd)) {
|
||||
sys_close(fd);
|
||||
sys_remove(tmp_path);
|
||||
return -1;
|
||||
}
|
||||
#else
|
||||
if (sys_fsync(fd)) {
|
||||
sys_close(fd);
|
||||
sys_remove(tmp_path);
|
||||
return -1;
|
||||
}
|
||||
#endif
|
||||
|
||||
close(fd);
|
||||
|
||||
if (rename_file_or_dir((string) { tmp_path, strlen(tmp_path) }, path)) {
|
||||
sys_remove(tmp_path);
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
int create_dir(string path)
|
||||
{
|
||||
char zt[PATH_MAX];
|
||||
|
||||
Reference in New Issue
Block a user