-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.c
140 lines (111 loc) · 2.99 KB
/
file.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
/*
* Copyright (c) 2012-2022 Israel Jacquez
* See LICENSE for details.
*
* Israel Jacquez <mrkotfw@gmail.com>
*/
#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include "file.h"
#include "math_utilities.h"
static ssusb_ret_t
_errno_convert(void)
{
switch (errno) {
case EXIT_SUCCESS:
return SSUSB_OK;
case EACCES:
return SSUSB_FILE_PERMISSION_ACCESS;
case ENAMETOOLONG:
case ENOENT:
return SSUSB_FILE_INVALID_PATH;
default:
return SSUSB_FILE_UNKNOWN_ERROR;
}
}
static ssusb_ret_t
_file_exists(const char *input_file)
{
if ((input_file == NULL) || (*input_file == '\0')) {
return SSUSB_FILE_INVALID_PATH;
}
/* Determine if the file exists */
struct stat stat_buffer;
if ((stat(input_file, &stat_buffer)) != 0) {
return SSUSB_FILE_NOT_EXIST;
}
/* Determine if the path is a file */
if ((stat_buffer.st_mode & S_IFMT) != S_IFREG) {
return SSUSB_FILE_NOT_FILE;
}
return SSUSB_OK;
}
ssusb_ret_t
file_read(const char *input_file, void **buffer, size_t *len)
{
assert(buffer != NULL);
assert(len != NULL);
ssusb_ret_t ret;
ret = SSUSB_OK;
*buffer = NULL;
*len = 0;
ret = _file_exists(input_file);
if (ret != SSUSB_OK) {
return ret;
}
FILE *file;
if ((file = fopen(input_file, "rb+")) == NULL) {
return _errno_convert();
}
/* Determine the size of file */
if ((fseek(file, 0, SEEK_END)) < 0) {
ret = _errno_convert();
goto error;
}
long tell;
if ((tell = ftell(file)) < 0) {
ret = _errno_convert();
goto error;
}
rewind(file);
*len = tell;
if (*len == 0) {
ret = SSUSB_FILE_EMPTY;
goto error;
}
if ((*buffer = malloc(*len)) == NULL) {
ret = SSUSB_INSUFFICIENT_MEMORY;
goto error;
}
(void)memset(*buffer, 0, *len);
if ((fread(*buffer, 1, *len, file)) != *len) {
ret = _errno_convert();
}
error:
fclose(file);
return ret;
}
ssusb_ret_t
file_write(const char *output_file, const void *buffer, size_t len)
{
assert(buffer != NULL);
assert(len != 0);
if ((output_file == NULL) || (*output_file == '\0')) {
return SSUSB_FILE_INVALID_PATH;
}
ssusb_ret_t ret;
ret = SSUSB_OK;
FILE *file;
if ((file = fopen(output_file, "wb+")) == NULL) {
return _errno_convert();
}
if ((fwrite(buffer, 1, len, file)) != len) {
ret = _errno_convert();
}
fclose(file);
return ret;
}