aboutsummaryrefslogtreecommitdiff
path: root/c10/ex00/main.c
blob: 0cc4470156da07ff37da84290296fb4bebda52fa (plain)
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
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   main.c                                             :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cacharle <charles.cabergs@gmail.com>       +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2019/07/11 18:06:43 by cacharle          #+#    #+#             */
/*   Updated: 2019/07/19 06:33:07 by cacharle         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#define BUFFER_SIZE 1024

int		read_write_file(int fildes)
{
	char	buf[BUFFER_SIZE];
	int		read_size;

	while ((read_size = read(fildes, buf, BUFFER_SIZE)) != 0)
	{
		if (read_size < 0)
			return (-1);
		write(STDOUT_FILENO, buf, read_size);
	}
	return (0);
}

int		main(int argc, char **argv)
{
	int		fildes;

	if (argc == 1)
	{
		write(STDERR_FILENO, "File name missing.\n", 20);
		return (1);
	}
	else if (argc > 2)
	{
		write(STDERR_FILENO, "Too many arguments.\n", 21);
		return (1);
	}
	if ((fildes = open(argv[1], O_RDONLY)) < 0)
	{
		write(STDERR_FILENO, "Cannot read file.\n", 18);
		return (1);
	}
	if ((read_write_file(fildes)) < 0)
	{
		write(STDERR_FILENO, "Cannot read file.\n", 18);
		return (1);
	}
	close(fildes);
	return (0);
}