-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathmerge.c
88 lines (79 loc) · 1.99 KB
/
merge.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 <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/time.h>
int readaline_and_out(FILE *fin, FILE *fout);
int
main(int argc, char *argv[])
{
FILE *file1, *file2, *fout;
int eof1 = 0, eof2 = 0;
long line1 = 0, line2 = 0, lineout = 0;
struct timeval before, after;
int duration;
int ret = 1;
if (argc != 4) {
fprintf(stderr, "usage: %s file1 file2 fout\n", argv[0]);
goto leave0;
}
if ((file1 = fopen(argv[1], "rt")) == NULL) {
perror(argv[1]);
goto leave0;
}
if ((file2 = fopen(argv[2], "rt")) == NULL) {
perror(argv[2]);
goto leave1;
}
if ((fout = fopen(argv[3], "wt")) == NULL) {
perror(argv[3]);
goto leave2;
}
gettimeofday(&before, NULL);
do {
if (!eof1) {
if (!readaline_and_out(file1, fout)) {
line1++; lineout++;
} else
eof1 = 1;
}
if (!eof2) {
if (!readaline_and_out(file2, fout)) {
line2++; lineout++;
} else
eof2 = 1;
}
} while (!eof1 || !eof2);
gettimeofday(&after, NULL);
duration = (after.tv_sec - before.tv_sec) * 1000000 + (after.tv_usec - before.tv_usec);
printf("Processing time = %d.%06d sec\n", duration / 1000000, duration % 1000000);
printf("File1 = %ld, File2= %ld, Total = %ld Lines\n", line1, line2, lineout);
ret = 0;
leave3:
fclose(fout);
leave2:
fclose(file2);
leave1:
fclose(file1);
leave0:
return ret;
}
/* Read a line from fin and write it to fout */
/* return 1 if fin meets end of file */
int
readaline_and_out(FILE *fin, FILE *fout)
{
int ch, count = 0;
do {
if ((ch = fgetc(fin)) == EOF) {
if (!count)
return 1;
else {
fputc(0x0a, fout);
break;
}
}
fputc(ch, fout);
count++;
} while (ch != 0x0a);
return 0;
}