-
Notifications
You must be signed in to change notification settings - Fork 1
/
hcp.c
49 lines (46 loc) · 1.04 KB
/
hcp.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
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define BUFFER_SIZE 1024
/**
* copier - copy the content of first argument to another.
*
* @file_from: source file.
*
* @file_to: destination file.
*/
int hcp(void)
{
int fd, fd2, r = 1, w, c;
char *buf = malloc(BUFFER_SIZE);
char *file_from = "/bin/ls", *file_to = "hbtn_ls";
fd2 = open(file_from, O_RDONLY);
if (fd2 == -1)
{
dprintf(STDERR_FILENO, "Error: Can't read from file %s\n", file_from);
exit(98);
}
umask(0);
fd = open(file_to, O_TRUNC | O_CREAT | O_WRONLY, 0777);
while (r > 0)
{
r = read(fd2, buf, BUFFER_SIZE);
w = write(fd, buf, r);
if (r == -1)
{
dprintf(STDERR_FILENO, "Error: Can't read from file %s\n", file_from);
exit(98);
}
if (fd == -1 || w == -1)
dprintf(STDERR_FILENO, "Error: Can't write to %s\n", file_to), exit(99);
}
c = close(fd);
if (c == -1)
dprintf(STDERR_FILENO, "Error: Can't close fd %d\n", fd), exit(100);
free(buf);
return (0);
}