-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathutils.c
More file actions
74 lines (62 loc) · 1.48 KB
/
utils.c
File metadata and controls
74 lines (62 loc) · 1.48 KB
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
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <errno.h>
#include <glib.h>
#include <glib/gstdio.h>
#include "utils.h"
ssize_t readn(int fd, void *vptr, size_t n)
{
size_t nleft;
ssize_t nread;
char *ptr;
ptr = vptr;
nleft = n;
while (nleft > 0) {
if ( (nread = read(fd, ptr, nleft)) < 0) {
if (errno == EINTR)
nread = 0; /* and call read() again */
else
return(-1);
} else if (nread == 0)
break; /* EOF */
nleft -= nread;
ptr += nread;
}
return(n - nleft); /* return >= 0 */
}
void rawdata_to_hex (const unsigned char *rawdata, char *hex_str, int n_bytes)
{
static const char hex[] = "0123456789abcdef";
int i;
for (i = 0; i < n_bytes; i++) {
unsigned int val = *rawdata++;
*hex_str++ = hex[val >> 4];
*hex_str++ = hex[val & 0xf];
}
*hex_str = '\0';
}
int do_write_chunk (const unsigned char *checksum, const char *buf, int len)
{
char chksum_str[41];
int fd;
int n;
rawdata_to_hex (checksum, chksum_str, 20);
/* Don't write if the block already exists. */
if (g_access (chksum_str, F_OK) == 0)
return 0;
fd = open (chksum_str, O_WRONLY|O_CREAT,0666);
if (fd == -1) {
printf ("Failed to open block %s.\n", chksum_str);
return -1;
}
n = write (fd, buf, len);
if (n < 0) {
printf ("Failed to write chunk %s.\n", chksum_str);
close (fd);
return -1;
}
close(fd);
return 0;
}