2 Copyright © 2013 Alastair Stuart
4 This program is open source software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
21 #define VERSION "0.01"
23 char* readline(FILE* stream
)
29 long int curr_pos
= ftell(stream
);
31 int c
= fgetc(stream
);
32 while (c
!= '\n' && c
!= EOF
)
38 fseek(stream
, curr_pos
, SEEK_SET
);
41 char* line
= calloc(1, length
+ 1);
43 for (size_t i
= 0; i
< length
; i
++)
45 line
[i
] = fgetc(stream
);
49 fgetc(stream
); // move past the newline
54 void usage(char* program
)
56 printf("Usage: %s [options] [file1] [file2]\n", program
);
57 printf("Compares 2 sorted files line by line.\n"
59 " --help Print this message.\n"
60 " --version Show version info.\n"
62 "If only one file is given, standard input is used for the second file.\n");
65 int main(int argc
, char* argv
[])
67 static struct option long_options
[] = {
68 {"help", no_argument
, NULL
, 1},
69 {"version", no_argument
, NULL
, 2},
74 while ((c
= getopt_long(argc
, argv
, "",
75 long_options
, NULL
)) != -1)
83 printf("comm (mutos) v"VERSION
"\n");
86 fprintf(stderr
,"Run '%s --help' for usage.\n",
95 if ((argc
- optind
) < 1) {
96 fprintf(stderr
, "%s: missing operands\n"
97 "Run '%s --help' for usage.\n",
100 } else if ((argc
- optind
) == 1) {
101 file1
= fopen(argv
[optind
], "r");
103 } else if ((argc
- optind
) == 2) {
104 file1
= fopen(argv
[optind
], "r");
105 file2
= fopen(argv
[optind
+1], "r");
107 fprintf(stderr
, "%s: extra operand: %s\n",
108 argv
[0], argv
[optind
+2]);
112 char* line1
= readline(file1
);
113 char* line2
= readline(file2
);
115 while (!feof(file1
) || !feof(file2
))
117 if (line1
&& line2
) {
118 if (strcmp(line1
, line2
) == 0) {
119 printf("\t\t%s\n", (line1
? line1
: line2
));
121 printf("\t%s\n", line2
);
122 printf("%s\n", line1
);
127 printf("%s\n", line1
);
131 printf("\t%s\n", line2
);
137 line1
= readline(file1
);
138 line2
= readline(file2
);