wc: Added wc
[mutos-utils.git] / comm.c
blob39e8d3eec4138c00f844942780135b39a99c5b67
1 /*
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.
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
19 #include <getopt.h>
21 #define VERSION "0.01"
23 char* readline(FILE* stream)
25 if (feof(stream)) {
26 return NULL;
28 size_t length = 0;
29 long int curr_pos = ftell(stream);
31 int c = fgetc(stream);
32 while (c != '\n' && c != EOF)
34 length++;
35 c = fgetc(stream);
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);
47 line[length] = '\0';
49 fgetc(stream); // move past the newline
51 return line;
54 void usage(char* program)
56 printf("Usage: %s [options] [file1] [file2]\n", program);
57 printf("Compares 2 sorted files line by line.\n"
58 "\n"
59 " --help Print this message.\n"
60 " --version Show version info.\n"
61 "\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},
70 {NULL, 0, NULL, 0}
73 int c = 0;
74 while ((c = getopt_long(argc, argv, "",
75 long_options, NULL)) != -1)
77 switch (c)
79 case 1:
80 usage(argv[0]);
81 return 0;
82 case 2:
83 printf("comm (mutos) v"VERSION"\n");
84 return 0;
85 default:
86 fprintf(stderr,"Run '%s --help' for usage.\n",
87 argv[0]);
88 return 1;
92 FILE* file1 = NULL;
93 FILE* file2 = NULL;
95 if ((argc - optind) < 1) {
96 fprintf(stderr, "%s: missing operands\n"
97 "Run '%s --help' for usage.\n",
98 argv[0], argv[0]);
99 return 1;
100 } else if ((argc - optind) == 1) {
101 file1 = fopen(argv[optind], "r");
102 file2 = stdin;
103 } else if ((argc - optind) == 2) {
104 file1 = fopen(argv[optind], "r");
105 file2 = fopen(argv[optind+1], "r");
106 } else {
107 fprintf(stderr, "%s: extra operand: %s\n",
108 argv[0], argv[optind+2]);
109 return 1;
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));
120 } else {
121 printf("\t%s\n", line2);
122 printf("%s\n", line1);
125 } else {
126 if (line1) {
127 printf("%s\n", line1);
130 if (line2) {
131 printf("\t%s\n", line2);
134 free(line1);
135 free(line2);
137 line1 = readline(file1);
138 line2 = readline(file2);
141 return 0;