-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbufio.c
More file actions
90 lines (77 loc) · 2.02 KB
/
bufio.c
File metadata and controls
90 lines (77 loc) · 2.02 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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include "bufio.h"
#include "dir.h"
#include "misc.h"
#include "regex.h"
#define LINE_LEN 50
int openfiles(filenames_t *filenames, char *pattern) {
int flag = 0;
if (filenames == NULL) {
perror("Error filenames_t is null in bufio.c");
return flag = -1;
}
char *buffer = NULL;
FILE *fp = NULL;
size_t count = filenames -> count;
for (size_t i = 0; i < count; ++i) {
if (!isObjectFile(filenames->f_names[i])) {
fp = fopen (filenames->f_names[i], "r");
if (fp == NULL) {
return flag = -1;
}
while ((buffer = readline(fp)) != NULL) {
if (match(buffer, pattern)) {
prints(filenames->f_names[i]);
prints(":");
prints(buffer);
}
free(buffer);
}
fclose(fp);
}
}
free(buffer);
return flag;
}
char * readline(FILE *fp) {
if (fp == NULL) {
perror("Error on FILE * in bufio.c");
return NULL;
}
size_t curBufLen = LINE_LEN;
char *buffer = (char *) malloc(sizeof(char) * LINE_LEN);
if (buffer == NULL) {
perror("Error on char * buffer allocation");
return NULL;
}
size_t i;
int c;
for (i = 0; ((c = getc(fp)) != EOF) && c != '\n'; ++i) {
buffer[i] = c;
if (i == curBufLen - 2) {
curBufLen = i * 2;
char *temp = (char *) realloc(buffer, sizeof(char) * curBufLen);
if (temp == NULL) {
perror("Error on char * buffer reallocation");
return NULL;
}
buffer = temp;
}
}
if (c == '\n') {
buffer[i++] = c;
buffer[i] = '\0';
}
else if (c == EOF) {
buffer[i++] = '\n';
buffer[i] = '\0';
free(buffer);
return NULL;
}
return buffer;
}