-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2.c
More file actions
59 lines (50 loc) · 1.66 KB
/
Copy path2.c
File metadata and controls
59 lines (50 loc) · 1.66 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
48
49
50
51
52
53
54
55
56
57
58
59
/*
Name: Teagan Haddawy
Date: Tuesday Jan 6, 2026
Title: Lab 1 - Part 4
Description: Copies a file using system calls
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#define BUFFER_SIZE 2048
int main(int argc, char *argv[])
{
if (argc != 3) //checks for the 3 arguements needed
{
fprintf(stderr, "Usage: %s <src_filename> <dst_filename>", argv[0]); //throws error if not given
exit(1);
}
int src_fd = open(argv[1], O_RDONLY); //open the src file using system calls for read only
if (src_fd < 0)
{
perror("error opening file"); //error if opening fails
exit(1);
}
int dst_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644 ); //open destination file with write only permissions
if (dst_fd < 0)
{
perror("error opening destination file"); //error if cannot be opened
exit(1);
}
char *buf = malloc(BUFFER_SIZE); //allocated memory for buffer
if (buf == NULL) //error if memory allocation failed
{
perror("Memory allocation failed");
close(src_fd);
close(dst_fd);
exit(1);
}
ssize_t bytes_read;
while ((bytes_read = read(src_fd, buf, BUFFER_SIZE)) > 0) //read the bits from the source file
{
write(dst_fd, buf, bytes_read); //write it to the destination file
}
free(buf); //free memory
close(src_fd);
close(dst_fd);
printf("File copied using System Calls\n");
return 0;
}