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
141
142
143
144
145
146
147
148
149
150
151
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <assert.h>
#include <unistd.h>
#include "main.h"
#include "textFile.h"
textFile_t *text_file_new(char *s)
{
textFile_t *new;
char path[STR_PATH_SIZE];
assert(s != NULL);
if (isFillPath(s)) {
strcpy(path, s);
} else {
getcwd(path, STR_PATH_SIZE);
strcat(path, "/");
strcat(path, s);
}
new = malloc(sizeof(textFile_t));
new->file = strdup(path);
new->text = list_new();
return new;
}
static void createLine(list_t *list, char *p, int len)
{
char *line;
char *begin_line;
char *end_line;
int length_line = 0;
assert(list != NULL);
assert(p != NULL);
assert(len >= 0);
begin_line = p;
do {
end_line = memchr(begin_line, '\n', len);
if (end_line == NULL) {
break;
}
length_line = (int) (end_line - begin_line);
line = malloc((length_line + 1) * sizeof(char));
memset(line, 0, (length_line + 1) * sizeof(char));
strncpy(line, begin_line, length_line);
list_add(list, line);
len -= (length_line + 1);
begin_line = end_line + 1;
} while (begin_line != NULL);
}
/**
* Loads file *s and returns him formatted to textFile_t*
*/
textFile_t *text_file_load(char *s)
{
FILE *file;
textFile_t *ret;
char *p;
int file_length = 0;
struct stat buf;
assert(s != NULL);
if (lstat(s, &buf) < 0) {
error("Unable to get file status [%s]", s);
return NULL;
}
file_length = buf.st_size;
if ((file = fopen(s, "rb")) == NULL) {
error("Unable to open file for reading [%s]", s);
return NULL;
}
p = malloc(file_length * sizeof(char));
if (fread(p, file_length * sizeof(char), 1, file) != 1) {
error("Unable to read data from file [%s]", s);
fclose(file);
return NULL;
}
fclose(file);
ret = text_file_new(s);
createLine(ret->text, p, file_length);
free(p);
return ret;
}
/**
* Prints the text saved in *p into stdout
*/
void text_file_print(textFile_t *p)
{
int i;
assert(p != NULL);
debug("Printing file [%s]", p->file);
for (i = 0; i < p->text->count; i++) {
printf("%3d >> %s\n", i, (char *) p->text->list[i]);
}
}
void text_file_save(textFile_t *p)
{
int i;
FILE *file;
assert(p != NULL);
file = fopen(p->file, "wb");
for (i = 0; i < p->text->count; i++) {
fprintf(file, "%s\n", (char *) p->text->list[i]);
}
fclose(file);
}
/**
* Removes text saved in *p from the memory
*/
void text_file_destroy(textFile_t *p)
{
assert(p != NULL);
free(p->file);
list_destroy_item(p->text, free);
free(p);
}
|