-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCopyFile.c
More file actions
68 lines (55 loc) · 2.7 KB
/
CopyFile.c
File metadata and controls
68 lines (55 loc) · 2.7 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
60
61
62
63
64
65
66
67
68
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h> // read the number of the last error
#include <fcntl.h> // file descriptor CONSTANT mode values
int main (int argc, char *argv[]) {
/*
* File descriptor array.
* When we create our pipe, we give pipe() this array and it will
* put the reading[0] and writing[1] file descriptors for the pipe into it.
*/
int pipeFds[2];
int fileBytesLength;
char buffer[100];
char childBuffer[100];
// Check if 3 arguments were supplied.
if (argc != 3) {
//perror("Filecopy: filecopy.txt [target] [destination]. \n");
exit(1);
}
char* srcFile = argv[1];
char* dstFile = argv[2];
// Attempt to create a pipe.
if (pipe(pipeFds) < 0) {
printf("Something went wrong creating the pipe! %s\n", strerror(errno));
exit(1);
}
// Fork child process
switch(fork()) {
// If there was an errorforking a child process
case -1:
printf("Error forking child process. %s\n", strerror(errno));
exit(1);
// If the current executing process is a child process
// Read the file from upstream parent process and write it to a new file.
case 0:
close(pipeFds[1]); // Close writing end of pipe upstream.
ssize_t num_bytes_child = read(pipeFds[0], childBuffer, sizeof(childBuffer)); // Read file contents from upstream pipe into childBuffer
close(pipeFds[0]); // close reading upstream pipe when we're done with it
int targetDesc = open(dstFile, O_CREAT | O_WRONLY); // Open a file for writing, create file descriptor.
write(targetDesc, childBuffer, num_bytes_child); // Write contents of buffer to new file descriptor.
printf("Successfully done...\n");
// If the current process is the parent process.
// Read the file and send it down to the child process to write.
default:
close(pipeFds[0]); // close reading end of pipe downstream.
int fileInDesc = open(srcFile, O_RDONLY); // Read file into file descriptor
ssize_t num_bytes = read(fileInDesc, buffer, sizeof(buffer)); // Get number bytes to read
write(pipeFds[1], buffer, num_bytes); // Write bytes to child process.
close(pipeFds[1]); // Close writing downstream pipe when we're done with it.
printf("Successfully done...\n");
}
return 0;
}