Advertisement
heavenriver

analyzer.c

Nov 30th, 2013
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.91 KB | None | 0 0
  1.  /* exercise on UNIX file system */
  2.  /* useful characters: [] # */
  3.  
  4.  # include <stdio.h>
  5.  # include <string.h>
  6.  # include <fcntl.h> // for O_RDONLY
  7.  # include <stdlib.h> // for exit()
  8.  
  9.  # define errormsg(x) { puts(x); exit(1); }
  10.  # define SIZE 1024
  11.  
  12.  int main(int argc, char * argv[])
  13.     {
  14.      // performing checks on input formatting
  15.      if((argc < 2) || (argc > 3)) errormsg("Error: Improperly formatted input");
  16.      if((argc == 2) &&  (*(argv + 1)[0] == '-')) errormsg("Error: Improperly formatted input");
  17.      if((argc == 3) && (*(argv + 1)[0] != '-')) errormsg("Error: Improperly formatted input");
  18.      
  19.      // assigns filename
  20.      char *filename;
  21.      if(argc == 2) filename = *(argv + 1);
  22.      else filename = *(argv + 2);
  23.      
  24.      // opening file
  25.      int file = open(filename, O_RDONLY);
  26.      if(file == -1) errormsg("Error: open() unsuccessful");
  27.      
  28.      // analysing text
  29.      char *buffer[SIZE];
  30.      int chars, words, lines; // variables needed
  31.      chars = words = lines = 0;
  32.      int res = read(file, buffer, SIZE);
  33.      while(res)
  34.     {
  35.      int index = 0;
  36.      while(index < res)
  37.         {
  38.          chars++;
  39.          if(buffer[index] == '\0' || buffer[index] == ' ') words++;
  40.          if(buffer[index] == '\0') lines++;
  41.         }
  42.      res = read(file, buffer, SIZE);
  43.     }
  44.    
  45.      // printing results
  46.      printf("Chars: %d; Words: %d; Lines: %d", chars, words, lines);
  47.     }
  48.  
  49.  /* teacher's version: int newword = 1; checks if newword before words++, why?
  50.   * (it does cover for double spacing, but it does not cover for consecutive spaces longer than two chars)
  51.   * it also uses two variables each, e.g. words and tempwords, updates one, then assigns the value to the other and prints it at the end. why?
  52.   * if(continuous) { sleep(1); lseek(file, 0, SEEK_SET); } while(continuous);
  53.   * the external loop revolves around "continuous" (condition: argc == 3 && *(argv + 1)[0] == '-')
  54.   * why?
  55.   */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement