-
Notifications
You must be signed in to change notification settings - Fork 0
/
utility.h
70 lines (61 loc) · 2.34 KB
/
utility.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
#ifndef H_UTILITY
#define H_UTILITY
namespace util{
/**
* Returns a string (char*) allocated dynamically, use free() to free memory
* @return char pointer to text contents read from file. NULL if there were
* errors.
* @param fileName Path to file.
*/
char *read_file(const char *fileName);
/**
* Counts number of bytes bytes in file and returs that number.
* @return Size of file in bytes.
* @param stream Pointer to a FILE object that identifies the stream.
*/
const size_t get_file_size(FILE *stream);
/**
* Opens a file and checks errors. perror is printed in case of error opening file.
* @return FILE pointer in case of success, nullptr otherwise.
* @param file_path path to file.
* @param mode fopen mode.
*/
FILE *safe_fopen(const char* file_path, const char* mode);
/**
* Checks for errors before closing file.
* @return A non-zero value is returned in the case that the error indicator associated with the stream is set.
* Otherwise, zero is returned.
* @param stream Pointer to a FILE object that identifies the stream.
*/
const int safe_fclose(FILE *stream);
/**
* Copies data to a binary file, then can be readed using read_data() function.
* @return A non-zero value is returned in the case that the error indicator associated with the stream is set.
* Otherwise, zero is returned.
* @param file_path Path to file.
* @param data Ponter to the data to be copied.
* @param size Size (int bytes) of the data chunk.
*/
template<typename T>
int save_data(const char *file_path, T &data, size_t size){
FILE *f = safe_fopen(file_path, "wb+");
fwrite(data, size, 1, f);
return safe_fclose(f);
}
/**
* Reads data from a binary file generated by save_data() function, and stores it a new array of the specified type.
* Use read_data<float>(file_path) to get a pointer to an array of floats;
* @return Pointer to an array of contents
* @param file_path Path to file.
*/
template<typename T>
T* read_data(const char *file_path){
FILE *f = safe_fopen(file_path, "rb");
size_t size = get_file_size(f);
T* res = (T*)malloc(size);
fread(res, size, 1, f);
safe_fclose(f);
return res;
}
}
#endif