-
Notifications
You must be signed in to change notification settings - Fork 0
/
0-read_textfile.c
43 lines (42 loc) · 912 Bytes
/
0-read_textfile.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
#include <stdio.h>
#include "main.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
/**
* read_textfile - Reads a text file and prints it to the POSIX
* standard output.
* @filename: file.
* @letters: Number of letters it should read and print.
* Return: Actual number of letters it could read and print.
*/
ssize_t read_textfile(const char *filename, size_t letters)
{
int fd, res_read, res_write;
char *buf;
if (filename == NULL)
return (0);
fd = open(filename, O_RDONLY);
if (fd == -1)
return (0);
buf = malloc(sizeof(char) * letters);
if (buf == NULL)
return (0);
res_read = read(fd, buf, letters);
if (res_read == -1)
{
free(buf);
return (0);
}
res_write = write(STDOUT_FILENO, buf, res_read);
if (res_write == -1 || res_read != res_write)
{
free(buf);
return (0);
}
free(buf);
close(fd);
return (res_write);
}