-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy pathfile_write_read_numeric.c
96 lines (88 loc) · 1.74 KB
/
file_write_read_numeric.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
/* Helpers to write numbers to files. TODO also implement read and check results. */
#include "common.h"
/* Write an array of ints to a human readable text file.
*
* ints are newline separated.
*
* Return -1 on failure, 0 on success.
*/
int write_int_array_to_file(
char *path,
int *arr,
size_t len
) {
size_t i;
FILE *fp;
fp = fopen(path, "w");
if (fp == NULL) {
return -1;
}
for (i = 0; i < len; i++){
if (fprintf(fp, "%d\n", arr[i]) < 0) {
return -1;
}
}
if (EOF == fclose(fp)) {
return -1;
}
return 0;
}
/* Same as write_int_array_to_file but for floats.
*
* Floats are saved in exp notation
* with precision (decimal places) precision.
*/
int write_float_array_to_file(
char *path,
float *arr,
size_t len,
int precision
) {
size_t i;
FILE *fp;
fp = fopen(path, "w");
if (fp == NULL){
return -1;
}
for (i = 0; i < len; i++) {
if (fprintf(fp,"%.*e\n", precision, arr[i]) < 0) {
return -1;
}
}
if (EOF == fclose(fp)) {
return -1;
}
return 0;
}
int main(void) {
/* ints */
{
int array[] = {
0,
1,
-1,
12873453
};
write_int_array_to_file(
COMMON_TMPFILE_NAMED("int"),
array,
COMMON_ARRAY_SIZE(array)
);
}
/* floats */
{
float array[] = {
1.1f,
1.001f,
-1.1f,
1.23456e2
};
write_float_array_to_file(
COMMON_TMPFILE_NAMED("float"),
array,
COMMON_ARRAY_SIZE(array),
2
);
}
return EXIT_SUCCESS;
}