-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.c
456 lines (360 loc) · 10.8 KB
/
utils.c
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
/* File: utils.c */
/*
This file is a part of the Corrfunc package
Copyright (C) 2015-- Manodeep Sinha ([email protected])
License: MIT LICENSE. See LICENSE file under the top-level
directory at https://github.com/manodeep/Corrfunc/
*/
/*
A collection of C wrappers I use. Should be
very obvious. The ones that are not obvious
have comments before the function itself.
Bugs:
Please email me manodeep at gmail dot com
Ver 1.0: Manodeep Sinha, 2nd April, 2012
Ver 1.1: Manodeep Sinha, 14th June, 2012 - replaced
check_string_copy with a "real" wrapper to
snprintf.
Ver 1.2: Manodeep Sinha, Jan 8, 2012 - replaced
print_time with timeval and gettimeofday
*/
#include "utils.h"
/* #define __USE_XOPEN2K */
/* #define _XOPEN_SOURCE_EXTENDED */
/* #define _GNU_SOURCE */
void run_system_call(const char *execstring)
{
int status;
status=system(execstring);
if(status != EXIT_SUCCESS) {
fprintf(stderr,"ERROR: executing system command: \n`%s'\n...exiting\n",execstring);
perror(NULL);
exit(EXIT_FAILURE);
}
}
FILE * my_fopen(const char *fname,const char *mode)
{
FILE *fp=NULL;
fp = fopen(fname,mode);
if(fp == NULL) {
fprintf(stderr,"Could not open file `%s'\n",fname);
perror(NULL);
exit(EXIT_FAILURE);
}
return fp;
}
/*
The following function opens a file (if it already exists)
in append mode. If the file doesn't exist, then the function
creates one, calls the *header() function [which presumably
prints a header to the file] and then returns the file pointer.
As usual, you need to be careful with the file you are appending
to -> otherwise you might end up with a ginormous file. Usually,
I do a system("rm -f filename") before the loop where the file
might be created/modified and remove the file from previous
runs.
*/
FILE * my_fopen_carefully(const char *fname,void (*header)(FILE *))
{
FILE *fp = fopen(fname, "r");//note I am using fopen and not my_fopen.
if(fp == NULL) {
/*file does not exist -> open with "w" */
fp = my_fopen(fname,"w");//using my_fopen here.
(*header)(fp);/* print the header */
} else {
fclose(fp);
fp = my_fopen(fname,"a+");//open with append mode
}
return fp;
}
size_t my_fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
{
const size_t nwritten = fwrite(ptr, size, nmemb, stream);
if(nwritten != nmemb) {
fprintf(stderr,"I/O error (fwrite) has occured.\n");
fprintf(stderr,"Instead of reading nmemb=%zu, I got nread = %zu ..exiting\n",nmemb,nwritten);
perror(NULL);
exit(EXIT_FAILURE);
}
return nwritten;
}
size_t my_fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
size_t nread = fread(ptr, size, nmemb, stream);
if(nread != nmemb) {
fprintf(stderr,"I/O error (fread) has occured.\n");
fprintf(stderr,"Instead of reading nmemb=%zu, I got nread = %zu ..exiting\n",nmemb,nread);
perror(NULL);
exit(EXIT_FAILURE);
}
return nread;
}
int my_fseek(FILE *stream, long offset, int whence)
{
int err=fseek(stream,offset,whence);
if(err != 0) {
fprintf(stderr,"ERROR: Could not seek `%ld' bytes into the file..exiting\n",offset);
perror(NULL);
exit(EXIT_FAILURE);
}
return err;
}
int64_t copy_bytes_between_two_files(const size_t bytes, FILE *in, FILE *out)
{
char buffer[MAXLEN];
size_t bytes_written = 0;
if(bytes == 0) {
return 0;
}
while(bytes_written < bytes) {
if(fgets(buffer, MAXLEN, in) != NULL) {
fprintf(out, "%s", buffer);
bytes_written += strlen(buffer);
} else {
fprintf(stderr,"Encountered EOF..bytes_written = %zu expected to write bytes = %zu\n",
bytes_written, bytes);
return -1;
}
}
return bytes_written;
}
int64_t copy_bytes_with_pread(const size_t bytes, int in, int out, off_t offset)
{
char buffer[MAXLEN];
size_t bytes_written = 0;
int64_t bytes_read;
if(bytes == 0) {
return 0;
}
while(bytes_written < bytes) {
const int bytes_left = (bytes - bytes_written) > MAXLEN ? MAXLEN:(bytes - bytes_written);
if( (bytes_read = pread(in, buffer, bytes_left, offset)) > 0 ) {
offset += bytes_read;
if(write(out, buffer, bytes_read) != bytes_read) {
fprintf(stderr,"Could not write %"PRId64" bytes\n",bytes_read);
perror(NULL);
exit(EXIT_FAILURE);
} else {
bytes_written += bytes_read;
}
} else {
fprintf(stderr, "Could not read requested %zu bytes - only have copied bytes = %zu\n",
bytes, bytes_written);
perror(NULL);
exit(EXIT_FAILURE);
}
}
return bytes_written;
}
// A real wrapper to snprintf that will exit() if the allocated buffer length
// was not sufficient. Usage is the same as snprintf
int my_snprintf(char *buffer,int len,const char *format, ...)
{
va_list args;
int nwritten=0;
va_start(args,format);
nwritten=vsnprintf(buffer, (size_t) len, format, args );
va_end(args);
if (nwritten > len || nwritten < 0) {
fprintf(stderr,"ERROR: printing to string failed (wrote %d characters while only %d characters were allocated)\n",nwritten,len);
fprintf(stderr,"Increase `len' in the header file ..exiting\n");
exit(EXIT_FAILURE);
}
return nwritten;
}
//Taken from the inter-webs: http://stackoverflow.com/questions/1024389/print-an-int-in-binary-representation-using-c
char * int2bin(int a, char *buffer, int buf_size)
{
buffer += (buf_size - 1);
for (int i = 31; i >= 0; i--) {
*buffer-- = (a & 1) + '0';
a >>= 1;
}
return buffer;
}
/*
I like this particular function. Generic replacement for printing
(in meaningful units) the actual execution time of a code/code segment.
The function call should be like this:
---------------------------
struct timeval t_start,t_end;
gettimeofday(&t_start,NULL);
do_something();
gettimeofday(&t_end,NULL);
print_time(t_start,t_end,"do something");
---------------------------
if the code took 220 mins 30.1 secs
-> print_time will output `Time taken to execute `do something' = 3 hours 40 mins 30.1 seconds
(code can be easily extended to include `weeks' as a system of time unit. left to the reader)
*/
void print_time(struct timeval t0,struct timeval t1,const char *s)
{
double timediff = difftime(t1.tv_sec,t0.tv_sec);
double ratios[] = {24*3600.0, 3600.0, 60.0, 1};
char units[4][10] = {"days", "hrs" , "mins", "secs"};
int which = 0;
double timeleft = timediff;
double time_to_print;
fprintf(stderr,"Time taken to execute '%s' = ",s);
if(timediff < ratios[2]) {
fprintf(stderr,"%6.3lf secs",1e-6*(t1.tv_usec-t0.tv_usec) + timediff);
} else {
while (which < 4) {
time_to_print = floor(timeleft/ratios[which]);
if (time_to_print > 1) {
timeleft -= (time_to_print*ratios[which]);
fprintf(stderr,"%5d %s",(int)time_to_print,units[which]);
}
which++;
}
}
fprintf(stderr,"\n");
}
//wrapper for realloc. varname should contain the name of the
//variable being re-allocated -> helps debugging in case of a crash.
void* my_realloc(void *x,size_t size,int64_t N,const char *varname)
{
void *tmp = realloc(x,N*size);
if (tmp==NULL) {
fprintf(stderr,"ERROR: Could not reallocate for %"PRId64" elements with %zu size for variable `%s' ..aborting\n",N,size,varname);
my_free((void **) &x);
perror(NULL);
exit(EXIT_FAILURE);
}
return tmp;
}
void* my_malloc(size_t size,int64_t N)
{
void *x = NULL;
x = malloc(N*size);
if (x==NULL){
fprintf(stderr,"malloc for %"PRId64" elements with %zu bytes failed..aborting\n",N,size);
perror(NULL);
exit(EXIT_FAILURE);
}
return x;
}
void* my_calloc(size_t size,int64_t N)
{
void *x = NULL;
x = calloc((size_t) N, size);
if (x==NULL) {
fprintf(stderr,"malloc for %"PRId64" elements with %zu size failed..aborting\n",N,size);
perror(NULL);
exit(EXIT_FAILURE);
}
return x;
}
//real free. Use only if you are going to check the
//pointer variable afterwards for NULL.
void my_free(void ** x)
{
/* my_free(void *x) would also free the
memory but then x would be a local variable
and the pointer itself in the calling routine
could not be set to NULL. Hence the pointer
to pointer business.
*/
if(*x!=NULL)
free(*x);//free the memory
*x=NULL;//sets the pointer in the calling routine to NULL.
}
void **matrix_malloc(size_t size,int64_t nrow,int64_t ncol)
{
void **m;
m = (void **) my_malloc(sizeof(void *),nrow);
for(int i=0;i<nrow;i++)
m[i] = (void *) my_malloc(size,ncol);
return m;
}
void **matrix_calloc(size_t size,int64_t nrow,int64_t ncol)
{
void **m;
m = (void **) my_calloc(sizeof(void *),nrow);
for(int i=0;i<nrow;i++)
m[i] = (void *) my_calloc(size,ncol);
return m;
}
void matrix_free(void **m,int64_t nrow)
{
for(int i=0;i<nrow;i++)
free(m[i]);
free(m);
}
void *** volume_malloc(size_t size,int64_t nrow,int64_t ncol,int64_t nframe)
{
void ***v;
v = (void ***) my_malloc(sizeof(void **),nrow);
for(int i=0;i<nrow;i++) {
v[i] = (void *) my_malloc(sizeof(void *),ncol);
for(int j=0;j<ncol;j++) {
v[i][j] = my_malloc(size,nframe);
}
}
return v;
}
void *** volume_calloc(size_t size,int64_t nrow,int64_t ncol,int64_t nframe)
{
void ***v;
v = (void ***) my_malloc(sizeof(void **),nrow);
for(int i=0;i<nrow;i++) {
v[i] = (void *) my_malloc(sizeof(void *),ncol);
for(int j=0;j<ncol;j++) {
v[i][j] = my_calloc(size,nframe);
}
}
return v;
}
void volume_free(void ***v,int64_t nrow,int64_t ncol)
{
for(int i=0;i<nrow;i++) {
for(int j=0;j<ncol;j++) {
free(v[i][j]);
}
free(v[i]);
}
free(v);
}
int64_t getnumlines(const char *fname,const char comment)
{
FILE *fp= NULL;
const int MAXLINESIZE = 10000;
int64_t nlines=0;
char str_line[MAXLINESIZE];
fp = my_fopen(fname,"rt");
while(1){
if(fgets(str_line, MAXLINESIZE,fp)!=NULL) {
//WARNING: this does not remove white-space. You might
//want to implement that (was never an issue for me)
if(str_line[0] !=comment)
nlines++;
} else
break;
}
fclose(fp);
return nlines;
}
int test_all_files_present(const int nfiles, ...)
{
/* sets i'th bit for i'th missing file
return value is 0 *iff* all files are present
and readable.
*/
int absent=0;
va_list filenames;
va_start(filenames, nfiles);
assert(nfiles <= 31 && "Can only test for 31 files simultaneously");
for(int i=0;i<nfiles;i++) {
const char *f = va_arg(filenames, const char *);
FILE *fp = fopen(f,"r");
if(fp == NULL) {
absent |= 1;
} else {
fclose(fp);
}
absent <<= 1;
}
va_end(filenames);
return absent;
}
/* #undef __USE_XOPEN2K */