-
Notifications
You must be signed in to change notification settings - Fork 0
/
read_file.cpp
111 lines (90 loc) · 2.3 KB
/
read_file.cpp
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
//@file
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <assert.h>
#include <time.h>
#include "onegin.h"
/*!
@brief This program have two ways to sort input text,\n starting with first char of line or last char of line
*/
void work_file(int *size, struct pointer_on_line** lineptr, char** text, const char* input, int* countline)
{
assert(size);
assert(lineptr);
assert(input);
assert(countline);
*text = readFile (input, size); // without *
*countline = get_line (*text, *size);
*lineptr = (struct pointer_on_line*) calloc (*countline, sizeof(struct pointer_on_line));
get_ptr(*text, *lineptr, *size);
}
/*!
Read input file to text
\param[in] str filename
\param[out] size size of file
\return text
*/
char *readFile (const char* str, int *size, const char* chmod)
{
assert (size);
assert (str);
FILE *fp = NULL;
if ((fp = fopen(str, chmod)) == NULL)
{
printf("Cannot find text\n");
system("pause");
exit(0);
}
fseek (fp, 0L, SEEK_END);
*size = (int) ftell(fp);
char *text = (char *) calloc(*size + 1, sizeof(char));
fseek (fp, 0L, SEEK_SET);
fread (text, sizeof(char), *size, fp);
text[*size] = '\0';
fclose (fp);
return text;
}
/*!
\param[in] str1 first cheking string
\param[in] str2 second cheking string
\return true or false
*/
int get_line (char* text, int size)
{
assert (text);
int countline = 0;
for (int i = 0; i < size; i++)
{
if ((text[i] == '\n' || text[i] == '\0') &&
(text[i+1] != '\n' && text[i+1] != '\0'))
{
countline++;
text[i] = '\0';
}
}
countline++;
text[size-1] = '\0';
return countline;
}
/*!
Get pointers to the beginning of line
\param[in] text input text
\param[out] lineptr array of pointers on string
\param[in] size length input text
*/
void get_ptr (char* text, struct pointer_on_line* lineptr, int size)
{
assert (text);
assert (lineptr);
int l = 0, i = 1;
lineptr[0].start = text;
for (; i < size-1; i++)
{
if (text[i] == '\0' && text[i - 1] != '\0')
lineptr[l++].end = text + i - 1;
if (text[i] == '\0' && text[i + 1] != '\0')
lineptr[l].start = text + i + 1;
}
// lineptr[l].end = text + i;
}