-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem-2
More file actions
47 lines (38 loc) · 1.07 KB
/
problem-2
File metadata and controls
47 lines (38 loc) · 1.07 KB
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
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#define BUF_SIZE 1024
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <source file> <destination file>\n", argv[0]);
return 1;
}
int src_fd = open(argv[1], O_RDONLY);
if (src_fd == -1) {
perror("Error opening source file");
return 1;
}
int dest_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (dest_fd == -1) {
perror("Error opening destination file");
close(src_fd);
return 1;
}
char buffer[BUF_SIZE];
ssize_t bytes_read, bytes_written;
while ((bytes_read = read(src_fd, buffer, BUF_SIZE)) > 0) {
bytes_written = write(dest_fd, buffer, bytes_read);
if (bytes_written != bytes_read) {
perror("Error writing to destination file");
close(src_fd);
close(dest_fd);
return 1;
}
}
if (bytes_read == -1) {
perror("Error reading source file");
}
close(src_fd);
close(dest_fd);
return 0;
}