From 6f5d21170297f1b423913febe4a6b578c27de5f0 Mon Sep 17 00:00:00 2001
From: Anonymous
Date: Tue, 17 Jun 2008 23:57:05 -0700
Subject: [PATCH] Added a basic implementation of wc.
new file: wc.c
---
coreutils/wc.c | 119 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 119 insertions(+)
create mode 100644 coreutils/wc.c
diff --git a/coreutils/wc.c b/coreutils/wc.c
new file mode 100644
index 0000000..8efea7e
--- /dev/null
+++ b/coreutils/wc.c
@@ -0,0 +1,119 @@
+/* wc.c for Anonix.
+ * not quite POSIX yet; need to implement the -L flag.
+ */
+
+#include
+#include /* fuck off, C99 rocks. */
+#include
+#include
+#include
+#include
+
+typedef struct {
+ bool print_bytes, print_words, print_lines;
+} options;
+
+int print_info(FILE *file, options *opts, char *program_name, char *filename)
+{
+ int ret = EXIT_SUCCESS;
+
+ if(!file) {
+ fprintf(stderr, "%s: %s: No such file or directory\n",
+ program_name, filename);
+ ret = EXIT_FAILURE;
+ }
+ /* collect file information. */
+ else {
+ size_t bytes = 0, lines = 0, words = 0;
+ int c = fgetc(file);
+ bool in_word = false;
+
+ while(c != EOF) {
+ bytes++;
+ if(c == '\n')
+ lines++;
+ if(!in_word && !isspace(c))
+ in_word = true;
+ else if(in_word && isspace(c)) {
+ words++;
+ in_word = false;
+ }
+ c = fgetc(file);
+ }
+
+ /* print file information. */
+ if(opts->print_lines)
+ printf("%zu ", lines);
+ if(opts->print_words)
+ printf("%zu ", words);
+ if(opts->print_bytes)
+ printf("%zu ", bytes);
+ printf("%s\n", filename);
+ fclose(file);
+ }
+
+ return ret;
+}
+
+int main(int argc, char *argv[])
+{
+ options opts;
+ bool default_options = true, found_file = false;
+ char *program_name = argv[0];
+ int option, i, ret = EXIT_SUCCESS;
+
+ opts.print_bytes = false;
+ opts.print_words = false;
+ opts.print_lines = false;
+
+ /* get short options. */
+ while((option = getopt(argc, argv, "cwlL")) != -1) {
+ default_options = false;
+ switch(option) {
+ case 'c':
+ opts.print_bytes = true;
+ break;
+ case 'w':
+ opts.print_words = true;
+ break;
+ case 'l':
+ opts.print_lines = true;
+ break;
+ }
+ }
+
+ /* get long options. */
+ for(i = 1; i < argc; ++i) {
+ if(!strcmp(argv[i], "--bytes") || !strcmp(argv[i], "--chars")) {
+ default_options = false;
+ opts.print_bytes = true;
+ }
+ else if(!strcmp(argv[i], "--words")) {
+ default_options = false;
+ opts.print_bytes = true;
+ }
+ else if(!strcmp(argv[i], "--lines")) {
+ default_options = false;
+ opts.print_bytes = true;
+ }
+ }
+
+ /* set default options if no options given. */
+ if(default_options)
+ opts.print_bytes = opts.print_words = opts.print_lines = true;
+
+ /* look for files. */
+ for(i = 1; i < argc; ++i) {
+ if(strncmp(argv[i], "--", 2) && strncmp(argv[i], "-", 1)) {
+ found_file = true;
+ ret |= print_info(fopen(argv[i], "rb"), &opts,
+ program_name, argv[i]);
+ }
+ }
+
+ /* use stdin if no file found. */
+ if(!found_file)
+ print_info(stdin, &opts, program_name, "");
+
+ return ret;
+}
--
2.11.4.GIT