This repository has been archived by the owner on Jan 31, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge_3616.c
87 lines (71 loc) · 1.57 KB
/
merge_3616.c
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#define BUFFSIZE 4096
char buff[BUFFSIZE]; //buffer for reading and writing
char* err; //error message
int main(int argc, char** argv){
if (argc != 4)
{
perror("Not sufficient number of arguments!");
exit(1);
}
int fd1 = open(argv[1], O_RDONLY);
int fd2 = open(argv[2], O_RDONLY);
int fd3 = open(argv[3], O_CREAT | O_WRONLY | O_TRUNC, S_IRWXU);
int n;
if (fd1 < 0)
{
sprintf(err, "%s %s", argv[1], "file does not exist!"); //it gives error in my local machine
// (segmentation fault: core dumped)
//most probably because of virtual machine
// but works well in mac
perror(err);
exit(1);
}
if (fd2 < 0)
{
sprintf(err, "%s %s", argv[2], "file does not exist!");
perror(err);
exit(1);
}
if (fd3 < 0)
{
sprintf(err, "%s %s", argv[3], "file does not exist!");
perror(err);
exit(1);
}
while((n = read(fd1, buff, BUFFSIZE)) > 0)
{
if(write(fd3, buff, n) != n)
{
perror("Write of the first file failed!");
exit(1);
}
}
if (n < 0)
{
perror("Could not read first file!");
exit(1);
}
while ((n = read(fd2, buff, BUFFSIZE)) > 0)
{
if (write(fd3, buff, n) != n)
{
perror("Write of the second file failed!");
exit(1);
}
}
if (n < 0)
{
perror("Could not read second file!");
exit(1);
}
close(fd1);
close(fd2);
close(fd3);
exit(0);
}