read.c
1 /* ************************************************************************** */ 2 /* */ 3 /* ::: :::::::: */ 4 /* read.c :+: :+: :+: */ 5 /* +:+ +:+ +:+ */ 6 /* By: gychoi <gychoi@student.42seoul.kr> +#+ +:+ +#+ */ 7 /* +#+#+#+#+#+ +#+ */ 8 /* Created: 2022/12/21 00:51:06 by gychoi #+# #+# */ 9 /* Updated: 2023/01/03 23:39:04 by gychoi ### ########.fr */ 10 /* */ 11 /* ************************************************************************** */ 12 13 #include "fdf.h" 14 15 static t_coord *get_coord(t_map *map, char *line, int index_y) 16 { 17 char **vars_x; 18 int i; 19 int var_z; 20 t_coord *coord; 21 22 vars_x = ft_split(line, ' '); 23 coord = fdf_malloc(sizeof(t_coord) * map->width); 24 i = 0; 25 while (vars_x && vars_x[i]) 26 { 27 var_z = ft_atoi(vars_x[i]); 28 coord[i] = init_coord(i - map->x_origin, \ 29 index_y - map->y_origin, var_z); 30 if (var_z > map->z_max) 31 map->z_max = var_z; 32 if (var_z < map->z_min) 33 map->z_min = var_z; 34 free(vars_x[i++]); 35 } 36 free(vars_x); 37 return (coord); 38 } 39 40 static void check_valid_file(char *path) 41 { 42 int i; 43 44 i = ft_strlen(path); 45 if (i < 5) 46 fdf_error("Error: Not a valid file "); 47 if (path[i - 1] != 'f' || path[i - 2] != 'd' \ 48 || path[i - 3] != 'f' || path [i - 4] != '.') 49 fdf_error("Error: Not a valid file "); 50 } 51 52 static int count_width(char *line) 53 { 54 int count; 55 char **vars_x; 56 57 vars_x = ft_split(line, ' '); 58 count = 0; 59 while (vars_x && vars_x[count]) 60 { 61 free(vars_x[count]); 62 count++; 63 } 64 free(vars_x); 65 return (count); 66 } 67 68 static void read_map_info(t_fdf *fdf, char *path) 69 { 70 int fd; 71 int width; 72 int height; 73 char *read_line; 74 75 check_valid_file(path); 76 fd = fdf_open(path, O_RDONLY); 77 read_line = get_next_line(fd); 78 width = count_width(read_line); 79 height = 1; 80 while (1) 81 { 82 free(read_line); 83 read_line = get_next_line(fd); 84 if (read_line == NULL) 85 break ; 86 height++; 87 } 88 fdf->map.width = width; 89 fdf->map.height = height; 90 fdf_close(fd); 91 } 92 93 void read_file(t_fdf *fdf, char *path) 94 { 95 int fd; 96 int index_y; 97 char *read_line; 98 99 read_map_info(fdf, path); 100 fdf->map.x_origin = fdf->map.width / 2; 101 fdf->map.y_origin = fdf->map.height / 2; 102 fd = fdf_open(path, O_RDONLY); 103 fdf->coords = fdf_malloc(sizeof(t_coord *) * fdf->map.height); 104 index_y = 0; 105 while (1) 106 { 107 read_line = get_next_line(fd); 108 if (read_line == NULL) 109 break ; 110 fdf->coords[index_y] = get_coord(&fdf->map, read_line, index_y); 111 index_y++; 112 free(read_line); 113 } 114 set_coord_margin(fdf); 115 fdf_close(fd); 116 }