-
Notifications
You must be signed in to change notification settings - Fork 0
/
sample.c
64 lines (57 loc) · 1.96 KB
/
sample.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* sample.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lsauvage <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/02/07 18:30:58 by lsauvage #+# #+# */
/* Updated: 2018/02/14 16:47:58 by lsauvage ### ########.fr */
/* */
/* ************************************************************************** */
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int readlinewidth(int fd)
{
char buff[2];
size_t nbread;
(void) memset((void *) buff, 0, (size_t) 2);
nbread = read(fd, (void *) buff, (size_t) 2);
if (nbread <= 0)
return (-1);
buff[1] = '\0';
return (atoi(buff));
}
void readandprintlines(int fd, size_t linewidth)
{
char *buff;
size_t nbread;
buff = (char *) malloc(sizeof(*buff) * (linewidth + 1));
if (buff == NULL)
return ;
(void) memset((void *) buff, 0, linewidth + 1);
while ((nbread = read(fd, (void *) buff, linewidth)) != 0)
{
printf("%s", buff);
(void) memset((void *) buff, 0, linewidth);
}
free(buff);
return ;
}
int main(void)
{
int fd;
int linewidth;
fd = open("./file.txt", O_RDONLY);
if (fd == -1)
return (-1);
linewidth = readlinewidth(fd);
if (linewidth == -1 || linewidth == 0)
return (-1);
readandprintlines(fd, (size_t) linewidth);
close(fd);
return (0);
}