-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0-read_textfile.c
50 lines (44 loc) · 1012 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
44
45
46
47
48
49
50
#include "main.h"
#include <stdio.h>
#include <stdlib.h>
/*******************START*******************/
/**
* read_textfile - functions; reads text_file & prints to_stdout.
* @filename:pointer: shows to the name of the file.
* @letters: Shows the No. of letters the
* function (read_textfile) should read & print.
*
* Return:Returns 0 if filename is NULL.
*
*
* ALX PROJECTS
*/
ssize_t read_textfile(const char *filename, size_t letters)
{
/****Declarations******/
int f_d;
ssize_t w_cnt;
ssize_t w_r;
char *buffer;
if (filename == NULL)
return (0);
f_d = open(filename, O_RDONLY);
if (f_d == -1)
return (0);
buffer = malloc(sizeof(char) * letters);
if (buffer == NULL)
{
free(buffer);
return (0);
}
w_r = read(f_d, buffer, letters);
if (w_r == -1)
return (0);
w_cnt = write(STDOUT_FILENO, buffer, w_r);
if (w_cnt == -1 || w_r != w_cnt)
return (0);
free(buffer);
close(f_d);
return (w_cnt);
}
/**************************STOP******************************/