|
| 1 | +#include "main.h" |
| 2 | + |
| 3 | +ssize_t cp(const char *file_from, const char *file_to); |
| 4 | + |
| 5 | +/** |
| 6 | + * main - copies the content of a file to another file. |
| 7 | + * |
| 8 | + * @argc: number of arguments. |
| 9 | + * @argv: arguments values. |
| 10 | + * |
| 11 | + * Return: (1) always success, otherwise EXIT_CODE. |
| 12 | + */ |
| 13 | +int main(int argc, char **argv) |
| 14 | +{ |
| 15 | + if (argc < 3) |
| 16 | + { |
| 17 | + dprintf(2, "Usage: cp file_from file_to\n"); |
| 18 | + exit(97); |
| 19 | + } |
| 20 | + |
| 21 | + cp(argv[1], argv[2]); |
| 22 | + |
| 23 | + return (1); |
| 24 | +} |
| 25 | + |
| 26 | +/** |
| 27 | + * cp - copies the content of a file to another file. |
| 28 | + * |
| 29 | + * @file_from: arguments values. |
| 30 | + * @file_to: number of arguments. |
| 31 | + * |
| 32 | + * Return: (1) always success, otherwise EXIT_CODE. |
| 33 | + */ |
| 34 | +ssize_t cp(const char *file_from, const char *file_to) |
| 35 | +{ |
| 36 | + int f_from_fd, fread, f_to_fd, perm, flags; |
| 37 | + char *buffer; |
| 38 | + |
| 39 | + flags = O_TRUNC | O_WRONLY | O_CREAT; |
| 40 | + perm = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH; |
| 41 | + |
| 42 | + f_from_fd = open(file_from, O_RDONLY); |
| 43 | + buffer = malloc(BUFFER_SIZE); |
| 44 | + fread = read(f_from_fd, buffer, BUFFER_SIZE); |
| 45 | + if (f_from_fd < 0 || buffer == NULL || fread < 0) |
| 46 | + { |
| 47 | + dprintf(2, "Error: Can't read from file %s\n", file_from); |
| 48 | + exit(98); |
| 49 | + } |
| 50 | + |
| 51 | + f_to_fd = open(file_to, flags, perm); |
| 52 | + if (f_to_fd < 0) |
| 53 | + { |
| 54 | + dprintf(2, "Error: Can't write to %s\n", file_to); |
| 55 | + exit(99); |
| 56 | + } |
| 57 | + |
| 58 | + while (fread != 0) |
| 59 | + { |
| 60 | + write(f_to_fd, buffer, fread); |
| 61 | + fread = read(f_from_fd, buffer, BUFFER_SIZE); |
| 62 | + } |
| 63 | + |
| 64 | + free(buffer); |
| 65 | + if (close(f_from_fd) < 0) |
| 66 | + { |
| 67 | + dprintf(2, "Error: Can't close fd %d\n", f_from_fd); |
| 68 | + exit(100); |
| 69 | + } |
| 70 | + if (close(f_to_fd) < 0) |
| 71 | + { |
| 72 | + dprintf(2, "Error: Can't close fd %d\n", f_to_fd); |
| 73 | + exit(100); |
| 74 | + } |
| 75 | + |
| 76 | + return (1); |
| 77 | +} |
0 commit comments