Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* exercise on UNIX file system */
- /* useful characters: [] # */
- # include <stdio.h>
- # include <string.h>
- # include <fcntl.h> // for O_RDONLY
- # include <stdlib.h> // for exit()
- # define errormsg(x) { puts(x); exit(1); }
- # define SIZE 1024
- int main(int argc, char * argv[])
- {
- // performing checks on input formatting
- if((argc < 2) || (argc > 3)) errormsg("Error: Improperly formatted input");
- if((argc == 2) && (*(argv + 1)[0] == '-')) errormsg("Error: Improperly formatted input");
- if((argc == 3) && (*(argv + 1)[0] != '-')) errormsg("Error: Improperly formatted input");
- // assigns filename
- char *filename;
- if(argc == 2) filename = *(argv + 1);
- else filename = *(argv + 2);
- // opening file
- int file = open(filename, O_RDONLY);
- if(file == -1) errormsg("Error: open() unsuccessful");
- // analysing text
- char *buffer[SIZE];
- int chars, words, lines; // variables needed
- chars = words = lines = 0;
- int res = read(file, buffer, SIZE);
- while(res)
- {
- int index = 0;
- while(index < res)
- {
- chars++;
- if(buffer[index] == '\0' || buffer[index] == ' ') words++;
- if(buffer[index] == '\0') lines++;
- }
- res = read(file, buffer, SIZE);
- }
- // printing results
- printf("Chars: %d; Words: %d; Lines: %d", chars, words, lines);
- }
- /* teacher's version: int newword = 1; checks if newword before words++, why?
- * (it does cover for double spacing, but it does not cover for consecutive spaces longer than two chars)
- * 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?
- * if(continuous) { sleep(1); lseek(file, 0, SEEK_SET); } while(continuous);
- * the external loop revolves around "continuous" (condition: argc == 3 && *(argv + 1)[0] == '-')
- * why?
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement