-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
116 lines (105 loc) · 2.75 KB
/
get_next_line.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
104
105
106
107
108
109
110
111
112
113
114
115
116
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mmounsif <mmounsif@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/12/17 20:15:06 by mmounsif #+# #+# */
/* Updated: 2024/12/23 14:11:15 by mmounsif ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static char *read_from_file(int fd, char *stash);
static int line_len(char *stash);
char *get_next_line(int fd)
{
char *line;
static char *stash;
char *temp;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
if (!stash)
{
stash = ft_strdup("");
if (!stash)
return (NULL);
}
stash = read_from_file(fd, stash);
if (!stash || !*stash)
return (free(stash), stash = NULL, NULL);
if (!ft_strchr(stash, '\n'))
{
line = ft_strdup(stash);
return (free(stash), stash = NULL, line);
}
line = ft_substr(stash, 0, line_len(stash));
temp = ft_strdup(stash + line_len(stash));
free(stash);
stash = temp;
return (line);
}
static char *read_from_file(int fd, char *stash)
{
char *buf;
int bytes_read;
char *temp;
buf = malloc((BUFFER_SIZE + 1) * sizeof(char));
if (!buf)
return (NULL);
while (!ft_strchr(stash, '\n'))
{
bytes_read = read(fd, buf, BUFFER_SIZE);
if (bytes_read == -1)
return (free(buf), free(stash), NULL);
if (bytes_read == 0)
break ;
buf[bytes_read] = '\0';
temp = ft_strjoin(stash, buf);
free(stash);
stash = temp;
}
return (free(buf), stash);
}
static int line_len(char *stash)
{
int i;
i = 0;
while (stash[i])
{
if (stash[i] == '\n')
return (i + 1);
i++;
}
return (i);
}
// #include <fcntl.h>
// #include <stdio.h>
// #include <string.h>
// int main()
// {
// int fd;
// char *content;
// char *next_line;
// int count;
// fd = open("test.txt", O_CREAT | O_RDWR, 0644);
// if (fd < 0)
// {
// perror("Error opening file");
// return (1);
// }
// content = "Hello, World\nthis is a test\nThank you for your time\n42";
// write(fd, content, strlen(content));
// lseek(fd, 0, SEEK_SET);
// count = 0;
// while (1)
// {
// next_line = get_next_line(fd);
// if (!next_line)
// break;
// count++;
// printf("Line %d: %s", count, next_line);
// free(next_line);
// }
// close(fd);
// }