-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_ops.c
55 lines (48 loc) · 1.18 KB
/
file_ops.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
#include "file_ops.h"
#include <stdio.h>
#include <stdlib.h>
/**
* @brief Read a file.
* @param fileName, the name of the file
* @return the text from the file
*/
char * read_file(char * fileName, unsigned int *retLength) {
long int size = 0;
FILE *file = fopen(fileName, "rb");
if(!file) {
fputs("File error.\n", stderr);
exit(1);
}
fseek(file, 0, SEEK_END);
size = ftell(file);
if(retLength != NULL) {
*retLength = (unsigned int)size;
}
rewind(file);
char * result = (char *) malloc(size +1);
result[size]= '\0';
if(!result) {
fputs("Memory error.\n", stderr);
exit(1);
}
if(fread(result, sizeof(char), size, file) != size) {
fputs("Read error.\n", stderr);
exit(1);
}
fclose(file);
return result;
}
/**
* @brief Write X amount of chars to a file
* @param fileName, the name of the file
* @param content, the content to write X from
* @param size, the X amount of chars
*/
void write_file(char * fileName, char * content, int size) {
FILE *fp = fopen(fileName, "w");
if(fp == NULL) {
printf("Error! Could not open file %s", fileName);
exit(1);
}
fwrite(content, sizeof(char), size, fp);
}