-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsafe_stdlib.c
More file actions
118 lines (98 loc) · 2.23 KB
/
Copy pathsafe_stdlib.c
File metadata and controls
118 lines (98 loc) · 2.23 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include <unistd.h>
#include <string.h>
#include <sys/mman.h>
#include <stdio.h>
#include "safe_stdlib.h"
void *safeMalloc(size_t size)
{
void *alloc = malloc(size);
if (!alloc)
{
perror("Error: malloc");
exit(EXIT_FAILURE);
}
return alloc;
}
FILE *safeFopen(const char *path, const char *mode)
{
FILE *file = fopen(path, mode);
if (!file)
{
perror("Error: fopen");
exit(EXIT_FAILURE);
}
return file;
}
void safeFseek(FILE *stream, long offset, int whence)
{
if (fseek(stream, offset, whence))
{
perror("Error: fseek");
exit(EXIT_FAILURE);
}
}
void *safeMmap(void *start, size_t length, int prot , int flags, int fd, off_t offset)
{
void *alloc = mmap(start, length, prot, flags, fd, offset);
if (alloc == MAP_FAILED)
{
perror("Error: mmap");
exit(EXIT_FAILURE);
}
return alloc;
}
void print_buffer(const char *name, int *buffer, int m, int n)
{
int j;
printf("%s\n", name);
for (j = 0; j < m; ++j)
{
int i;
int *buffer_m = buffer + n * j;
for (i = 0; i < n - 1; ++i)
printf("%d ", buffer_m[i]);
if (n > 0)
printf("%d\n", buffer_m[n - 1]);
}
}
void print_distances(const char *name, double *buffer, int m, int n)
{
int j;
printf("%s\n", name);
for (j = 0; j < m; ++j)
{
int i;
double *buffer_m = buffer + n * j;
for (i = 0; i < n - 1; ++i)
printf("%f ", buffer_m[i]);
if (n > 0)
printf("%f\n", buffer_m[n - 1]);
}
}
void print_time(const char *name, long time)
{
long time_ms = (time + 500000) / 1000000;
#ifndef NDEBUG
{
long minutes = time_ms / 60000;
double seconds = (time_ms % 60000) * 1e-3;
int len = strlen(name);
char buffer[31];
memset(buffer, ' ', 30);
buffer[30] = '\0';
if (len < 31)
strncpy(buffer, name, len);
fprintf(stderr, "%s", name);
while (len < 30)
{
len += 1;
fprintf(stderr, " ");
}
fprintf(stderr, "%ldm%.3fs\n", minutes, seconds);
}
#else
{
fprintf(stderr, "%ld\n", time_ms);
}
#endif
}