-
Notifications
You must be signed in to change notification settings - Fork 0
/
io.c
103 lines (84 loc) · 1.55 KB
/
io.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
92
93
94
95
96
97
98
99
100
101
102
103
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include "header.h"
/*char* read_file_descriptor(int fd, size_t *length)
{
//if(fd <= 0)
// return NULL;
int c;
size_t len = BUFFER_SIZE;
size_t pos = 0;
ssize_t res = 0;
char *buf = NULL;
buf = calloc(len, sizeof(char));
if(!buf)
p_error("error: %s: allocation failed\n", __func__);
printf("DEBUG: rfd1\n");
while((res = read(fd, &c, 1)) > 0)
{
//printf("DEBUG: res = %zu\n", res);
//printf("DEBUG: c = \'%c\'\n\n", c);
if(c == '\n')
{
printf("DEBUG: pos = %zd, c = \'%c\'\n", pos, c);
buf[pos] = '\0';
*length = pos;
return buf;
}
buf[pos++] = c;
printf("DEBUG: pos = %zd\n", pos);
if(pos >= len)
{
len += BUFFER_SIZE;
buf = realloc(buf, len);
if(!buf)
p_error("error: %s: allocation failed\n", __func__);
}
}
printf("DEBUG: rfd2\n");
free(buf);
*length = 0;
return NULL;
}*/
char* read_file_stream(FILE *stream)
{
assert(stream != NULL);
if(ferror(stream))
return NULL;
int c;
size_t len = BUFFER_SIZE;
size_t pos = 0;
char *buf = NULL;
buf = calloc(len, sizeof(char));
if(!buf)
p_error("error: %s: allocation failed\n", __func__);
while(1)
{
c = fgetc(stream);
if(c == '\n')
{
buf[pos] = '\0';
return buf;
}
else if(c == EOF)
{
if(pos != 0)
{
buf[pos] = '\0';
return buf;
}
free(buf);
return NULL;
}
buf[pos++] = c;
if(pos >= len)
{
len += BUFFER_SIZE;
buf = realloc(buf, len);
if(!buf)
p_error("error: %s: allocation failed\n", __func__);
}
}
}