-
Notifications
You must be signed in to change notification settings - Fork 0
/
copy_file.h
71 lines (61 loc) · 1.69 KB
/
copy_file.h
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
int copy_file(const char *srcfile, const char *dstfile)
{
# ifndef PATH_MAX
# define PATH_MAX 256
# endif // PATH_MAX
char tmpfile[PATH_MAX];
snprintf(tmpfile, sizeof(tmpfile), "%s.tmp", dstfile);
int fsrc = open(srcfile, O_RDONLY);
if (-1 == fsrc)
{
MLOG_ERROR("cannot read file %s. errmsg %d:%s",
srcfile, errno, strerror(errno));
return MDB_ERROR;
}
int fdst = open(tmpfile, O_WRONLY | O_WRONLY | O_CREAT, 0600);
if (-1 == fdst)
{
MLOG_ERROR("create file failure. file name %s, errmsg %d:%s",
tmpfile, errno, strerror(errno));
close(fsrc);
return MDB_ERROR;
}
char buf[4 * 1024];
ssize_t size = 0;
while (true)
{
size = read(fsrc, buf, sizeof(buf));
if (0 == size)
{
close(fsrc);
close(fdst);
if (0 != rename(tmpfile, dstfile))
{
MLOG_ERROR("rename file [%s] to file [%s] failure. errmsg %d:%s",
tmpfile, dstfile);
remove(tmpfile);
return MDB_ERROR;
}
return MDB_SUCCESS;
}
if (size < 0)
{
MLOG_ERROR("read file failure. file name %s, fd %d, errmsg %d:%s",
srcfile, fsrc, errno, strerror(errno));
goto err;
}
if (0 != writen(fdst, buf, size))
{
MLOG_ERROR("write file failure. file %s, fd %d, errmsg %d:%s",
tmpfile, fdst, errno, strerror(errno));
goto err;
}
}
err:
if (fsrc >= 0)
close(fsrc);
if (fdst >= 0)
close(fdst);
remove(tmpfile);
return MDB_ERROR;
}