84 lines
2.1 KiB
C
84 lines
2.1 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* ft_open.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: asargsya <asargsya@student.42yerevan.am> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2023/12/03 19:08:11 by asargsya #+# #+# */
|
|
/* Updated: 2023/12/03 23:36:29 by achubuko ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "ft_open.h"
|
|
|
|
t_file *ft_open(char *path)
|
|
{
|
|
t_file *file;
|
|
|
|
file = malloc(sizeof(t_file));
|
|
file->descriptor = open(path, O_RDONLY);
|
|
file->read_window_size = 4096;
|
|
file->read_window = malloc(sizeof(char) * file->read_window_size);
|
|
file->read_size = 0;
|
|
file->read_window_cursor = 0;
|
|
file->buffer = 0;
|
|
file->buffer_size = 0;
|
|
return (file);
|
|
}
|
|
|
|
void ft_growbuffer(t_file *f, ssize_t grow)
|
|
{
|
|
char *prev;
|
|
char *cur;
|
|
ssize_t pos;
|
|
|
|
prev = f->buffer;
|
|
cur = malloc(sizeof(char) * (f->buffer_size + grow));
|
|
pos = 0;
|
|
while (prev && cur && pos < f->buffer_size)
|
|
{
|
|
cur[pos] = prev[pos];
|
|
pos++;
|
|
}
|
|
while (cur && pos < f->buffer_size + grow)
|
|
{
|
|
cur[pos] = 0;
|
|
pos++;
|
|
}
|
|
// free(prev);
|
|
f->buffer = cur;
|
|
}
|
|
|
|
ssize_t ft_churn(t_file *f)
|
|
{
|
|
f->read_size = read(f->descriptor, f->read_window, f->read_window_size);
|
|
f->read_window_cursor = 0;
|
|
return (f->read_size);
|
|
}
|
|
|
|
ssize_t ft_buffer_line(t_file *f)
|
|
{
|
|
char *c;
|
|
ssize_t len;
|
|
|
|
ft_growbuffer(f, 100);
|
|
len = 0;
|
|
c = 0;
|
|
while (1)
|
|
{
|
|
if (f->read_window_cursor >= f->read_size)
|
|
{
|
|
ft_churn(f);
|
|
}
|
|
f->buffer[len] = f->read_window[f->read_window_cursor];
|
|
if (len + 1 >= f->buffer_size)
|
|
ft_growbuffer(f, 100);
|
|
if (f->read_window[f->read_window_cursor] == '\n')
|
|
return (len);
|
|
len++;
|
|
f->read_window_cursor++;
|
|
}
|
|
return (0);
|
|
}
|