-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlineno.c
91 lines (75 loc) · 1.96 KB
/
lineno.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
#include "lineno.h"
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <string.h>
#define MAXLINE 10000
struct _lineno_node_t {
position_t first_char;
struct _lineno_node_t * next;
};
size_t read_lineno(char * fd, position_t ** lineno) {
FILE * fp = fopen(fd, "r");
if (!fp) {
printf("Failed\n");
exit(1);
}
struct _lineno_node_t * ptr =
(struct _lineno_node_t *) malloc(sizeof(struct _lineno_node_t));
ptr->first_char = 0;
ptr->next = NULL;
struct _lineno_node_t * head = ptr;
size_t size = 1;
size_t pos = 0;
while (!feof(fp)) {
char c = fgetc(fp);
++pos;
if (c == '\n' || c == EOF) {
struct _lineno_node_t * next =
(struct _lineno_node_t *) malloc(sizeof(struct _lineno_node_t));
next->first_char = pos;
next->next = NULL;
ptr->next = next;
ptr = next;
++size;
}
}
// copy linked list into array
*lineno =
(position_t *) malloc(size * sizeof(struct _lineno_node_t));
ptr = head;
for (size_t j = 0; j < size; j++, ptr=ptr->next) {
(*lineno)[j] = ptr->first_char;
}
return size;
}
void get_lineno(position_t * lineno, size_t len, position_t pos,
size_t * row, size_t * col) {
size_t L = 0,
R = len - 1,
m;
*row = -1;
*col = -1;
while (L <= R) {
m = (L + R) / 2;
if (lineno[L] < pos && (L == len - 1 || pos < lineno[L + 1])) {
*row = L;
break;
}
if (pos < lineno[R] && (R == 0 || lineno[R - 1] < pos)) {
*row = R - 1;
break;
}
if (lineno[m] < pos) {
L = m + 1;
} else if (lineno[m] > pos) {
R = m - 1;
} else {
*row = m;
break;
}
}
if (*row != -1) {
*col = pos - lineno[*row];
}
}