piscine-rush02/ex00/dictparse.c

72 lines
1.4 KiB
C

#include "ft_io.h"
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#define MAX_LINE_LENGTH 1000
#define FILE_READ_ERROR -1
#define LINE_TOO_LONG -2
/*
* Copy to buf from file at `path' with `offset' continuously until
* either EOF, '\n', or `size' is reached. Return new offset.
*/
int readline(char *buf, int size, char *path, int offset)
{
char c;
int fd;
int bytes_read;
fd = open(path, O_RDONLY);
if (fd < 0)
return (FILE_READ_ERROR);
bytes_read = -1;
while (++bytes_read < offset)
if (read(fd, &c, sizeof(c)) <= 0)
return (FILE_READ_ERROR);
bytes_read = 0;
while (read(fd, &c, sizeof(c)) > 0 && bytes_read < size)
{
if (c == '\n')
break ;
*buf++ = c;
++bytes_read;
}
if (bytes_read == size)
return (LINE_TOO_LONG);
*buf = 0;
close(fd);
return (offset + bytes_read + 1);
}
int parse_line(char *line, char **key, char **value)
{
(void)line;
*key = "20";
*value = "twenty";
return (1);
}
int parse_dict(char *path, t_map_entry *map)
{
char buf[MAX_LINE_LENGTH];
int offset;
char *key;
char *value;
(void)map;
offset = 0;
for (int i = 0; i < 20; ++i)
{
offset = readline(buf, MAX_LINE_LENGTH, path, offset);
if (offset == FILE_READ_ERROR)
break ;
else if (offset == LINE_TOO_LONG)
return (0);
if (!parse_line(buf, &key, &value))
return (0);
ll_map_push(map, key, /* value */buf);
}
return (1);
}