-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmergie.c
64 lines (51 loc) · 1.25 KB
/
mergie.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
/*
** Merger for multiple shuffled MPI-tempered output files.
**
** Copyright (c) 2007 Alexei Podtelezhnikov
*/
#include<stdlib.h>
#include<stdio.h>
int main(int argc, char *argv[])
{
int i, j, files, *pos;
char *format, line[83];
FILE **f;
format = argv[1]; /* first argument is format */
files = argc - 2; /* the rest are file names */
f = (FILE **) malloc(files * sizeof(FILE *));
pos = (int *) malloc(files * sizeof(int));
if (f == NULL || pos == NULL) {
fprintf(stderr, "Memory Failure\n");
exit(EXIT_FAILURE);
}
for (i = 0; i < files; i++) {
f[i] = fopen(argv[i + 2], "r");
if (f[i] == NULL) {
fprintf(stderr, "Input Failure: %s\n", argv[i + 2]);
exit(EXIT_FAILURE);
}
}
for (i = 0; i < files; i++) {
while (fgets(line, sizeof(line), f[i]) != NULL
&& sscanf(line, format, pos + i) != 1)
pos[i] = EOF;
}
while (1) {
for (i = 0; i < files; i++)
if (pos[i] != EOF)
break;
for (j = i; i < files; i++)
if (pos[i] != EOF && pos[i] < pos[j])
j = i;
if (j == files)
break; /* we're done */
printf(format, pos[j]);
putchar('\n');
while (fgets(line, sizeof(line), f[j]) != NULL
&& sscanf(line, format, pos + j) != 1) {
printf("%s", line);
pos[j] = EOF;
}
}
return EXIT_SUCCESS;
}