osmo-sdr/utils/vmelinearize/src/utils.c @ master
1 | c46bad77 | Christian Daniel | #include <stdio.h>
|
---|---|---|---|
2 | #include <errno.h>
|
||
3 | #include <string.h>
|
||
4 | #include <sys/stat.h>
|
||
5 | #include "utils.h"
|
||
6 | |||
7 | void* loadFile(const char* filename, size_t* size) |
||
8 | {
|
||
9 | void* result = NULL; |
||
10 | struct stat statbuf; |
||
11 | FILE* f = NULL; |
||
12 | |||
13 | if(stat(filename, &statbuf) < 0) { |
||
14 | fprintf(stderr, "could not stat() file %s: %s\n", filename, strerror(errno)); |
||
15 | goto failed; |
||
16 | }
|
||
17 | |||
18 | if((result = calloc(1, statbuf.st_size)) == NULL) { |
||
19 | #ifdef WINDOWS
|
||
20 | fprintf(stderr, "failed to allocate %u bytes of memory\n", (size_t)statbuf.st_size); |
||
21 | #else
|
||
22 | fprintf(stderr, "failed to allocate %zu bytes of memory\n", (size_t)statbuf.st_size); |
||
23 | #endif
|
||
24 | goto failed; |
||
25 | }
|
||
26 | if((f = fopen(filename, "rb")) == NULL) { |
||
27 | fprintf(stderr, "failed to open %s: %s\n", filename, strerror(errno)); |
||
28 | goto failed; |
||
29 | }
|
||
30 | if(fread(result, 1, statbuf.st_size, f) != statbuf.st_size) { |
||
31 | fprintf(stderr, "could not read all bytes: %s\n", strerror(errno)); |
||
32 | goto failed; |
||
33 | }
|
||
34 | |||
35 | fclose(f); |
||
36 | *size = (size_t)statbuf.st_size; |
||
37 | return result; |
||
38 | |||
39 | failed:
|
||
40 | if(f != NULL) |
||
41 | fclose(f); |
||
42 | return NULL; |
||
43 | }
|