read_file.c
1 /* ************************************************************************** */ 2 /* */ 3 /* ::: :::::::: */ 4 /* read_file.c :+: :+: :+: */ 5 /* +:+ +:+ +:+ */ 6 /* By: ll-hotel <ll-hotel@student.42lyon.fr> +#+ +:+ +#+ */ 7 /* +#+#+#+#+#+ +#+ */ 8 /* Created: 2024/07/26 15:38:31 by ll-hotel #+# #+# */ 9 /* Updated: 2024/10/21 17:41:26 by ll-hotel ### ########.fr */ 10 /* */ 11 /* ************************************************************************** */ 12 13 #include "ft_basics.h" 14 #include "ft_dprintf.h" 15 #include "ft_vec.h" 16 #include "get_next_line.h" 17 #include "parsing.h" 18 #include <errno.h> 19 #include <stdlib.h> 20 #include <string.h> 21 #include <unistd.h> 22 #include <fcntl.h> 23 24 static int append_line(t_vec *file, char *line); 25 26 int read_file(char const *file_name, t_line **lines) 27 { 28 int fd; 29 t_vec file; 30 char *line; 31 32 fd = open(file_name, O_RDONLY); 33 if (fd == -1) 34 { 35 ft_dprintf(2, "Error\nCould not open file %s: %s\n", \ 36 file_name, strerror(errno)); 37 return (0); 38 } 39 vec_new(&file, sizeof(**lines)); 40 line = get_next_line(fd); 41 while (line) 42 { 43 if (!append_line(&file, line)) 44 return (0); 45 line = get_next_line(fd); 46 } 47 if (!vec_addback(&file, &(t_line){0})) 48 return (vec_clear(&file, free_line), 0); 49 *lines = file.array; 50 return (1); 51 } 52 53 static int append_line(t_vec *file, char *str) 54 { 55 t_line line; 56 char *newline; 57 58 newline = ft_strrchr(str, '\n'); 59 if (newline) 60 *newline = 0; 61 line_from_str(&line, str); 62 if (vec_addback(file, &line) == NULL) 63 { 64 free(str); 65 vec_clear(file, free_line); 66 return (0); 67 } 68 return (1); 69 }