Skip to content

Commit 197788a

Browse files
committed
task four: 3-cp.c - status: new
1 parent 4a8b86c commit 197788a

File tree

3 files changed

+84
-0
lines changed

3 files changed

+84
-0
lines changed

0x15-file_io/3-cp.c

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
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+
}

0x15-file_io/incitatous

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Why you should think twice before putting pictures on social media.
2+
(What you always wanted to know about @Incitatous)
3+
#PrivacyAware
4+
http://imgur.com/a/Mq1tc

0x15-file_io/main.h

+3
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66
#include <sys/types.h>
77
#include <sys/stat.h>
88
#include <fcntl.h>
9+
#include <stdio.h>
10+
11+
#define BUFFER_SIZE 1024
912

1013
ssize_t read_textfile(const char *, size_t);
1114
int create_file(const char *, char *);

0 commit comments

Comments
 (0)