-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadData.cpp
More file actions
115 lines (70 loc) · 2.12 KB
/
ReadData.cpp
File metadata and controls
115 lines (70 loc) · 2.12 KB
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
#include <stdio.h>
#include <assert.h>
#include "ReadData.h"
int size_of_file(FILE *fp) {
assert(fp != NULL);
fseek(fp, 0, SEEK_END);
int sz = (int)ftell(fp);
fseek(fp, 0, SEEK_SET);
return sz;
}
int number_of_symbs(const char *buf, size_t len, char symb) {
assert(buf != NULL);
int nSymbs = 0;
for (size_t i = 0; i < len; ++i) {
if (buf[i] == symb) {
nSymbs ++;
}
}
return nSymbs;
}
LinesData *create_pointer_arr(char *buf, size_t sz, int nLines) {
assert(buf != NULL);
assert(nLines >= 0);
LinesData *text = (LinesData*) calloc(nLines, sizeof(LinesData));
if (text == NULL) {
printf(" Sorry! Can't open your fie because it's too big\n");
}
for(int i = 0; i < nLines; i++) {
(text[i]).pointer = NULL;
(text[i]).len = 0;
}
(text[0]).pointer = buf;
int line = 1;
for(size_t i = 0; i < sz; ++i) {
if (buf[i] == '\n') {
buf[i] = '\0';
(text[line - 1]).len = (buf + i + 1) - (text[line - 1]).pointer;
if (line < nLines) {
(text[line]).pointer = buf + i + 1;
line ++;
}
}
}
return text;
}
char *read_data_from_file(FILE *fp, size_t sz) {
if (fp == NULL) {
printf("There's no file with text of poem\n");
}
char *buf = (char*) calloc(sz + 1, sizeof(char));
assert(buf != NULL);
size_t nRead = fread(buf, sizeof(char), sz, fp);
assert (nRead <= sz);
//printf("%d %d\n", nRead, sz);
buf[nRead] = '\n';
return buf;
}
void read_from_file(const char *InputFile, TextData *textdata) {
assert(textdata != NULL);
FILE *finput = fopen(InputFile , "rb" );
assert(finput != NULL);
textdata->sz = size_of_file(finput);
textdata->buf = read_data_from_file(finput, textdata->sz);
fclose(finput);
textdata->nLines = number_of_symbs(textdata->buf, textdata->sz, '\n');
if (textdata->buf[textdata->sz - 1] != '\n') {
textdata->nLines ++;
}
textdata->text = create_pointer_arr(textdata->buf, textdata->sz, textdata->nLines);
}