Advertisement
acobzew

sem4-problem2

Apr 24th, 2017
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.71 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #define MAX_INPUT_SIZE 100
  5. #define MAX_STR_LEN 100
  6. #define DEFAULT_N 10
  7.  
  8. void printHelpAndQuit()
  9. {
  10.     printf("This little useful program can print the last N lines of your input!\n");
  11.     printf("-n\tspecify number of lines to print (%d by default)\n", DEFAULT_N);
  12.     printf("-f\tspecify the file to read from\n");
  13.     printf("-h\tprint this message\n");
  14.     exit(0);
  15. }
  16.  
  17. int main(int argc, char const *argv[])
  18. {
  19.     char s[MAX_INPUT_SIZE][MAX_STR_LEN];
  20.     int n = 10, i = 0, j = 0;
  21.     FILE *f = stdin;
  22.  
  23.     for (i = 1; i < argc; i++)
  24.     {
  25.         if (strcmp(argv[i], "-f") == 0)
  26.         {
  27.             // Read from file
  28.             if (i + 1 < argc)
  29.             {
  30.                 //Try open file
  31.                 if ((f = fopen(argv[++i], "r")) == NULL)
  32.                 {
  33.                     printf("Error: Can not read file\n");
  34.                     printHelpAndQuit();
  35.                 }
  36.             }
  37.             else
  38.             {
  39.                 printf("Error: Specify file name\n");
  40.                 printHelpAndQuit();
  41.             }
  42.         }
  43.         else if (strcmp(argv[i], "-n") == 0)
  44.         {
  45.             //Redefine number of lines to print
  46.             if (i + 1 < argc)
  47.             {
  48.                 char *pEnd;
  49.                 n = strtol(argv[i + 1], &pEnd, 10);
  50.                 if (pEnd == argv[i + 1])
  51.                 {
  52.                     printf("Error: Argument -n is not valid number\n");
  53.                     printHelpAndQuit();
  54.                 }
  55.                 i++;
  56.             }
  57.             else
  58.             {
  59.                 printf("Error: Specify number of lines to print after -n\n");
  60.                 printHelpAndQuit();
  61.             }
  62.         }
  63.         else if (strcmp(argv[i], "-h") == 0)
  64.         {
  65.             printHelpAndQuit();
  66.         }
  67.         else
  68.         {
  69.             printf("Invalid parameter\n");
  70.             printHelpAndQuit();
  71.         }
  72.     }
  73.  
  74.     i = 0;
  75.     while (fscanf(f, "%s", s[i++]) != EOF);
  76.  
  77.     printf("\n");
  78.     if (n > i - 1)
  79.         printf("Too many lines to print!\n");
  80.     else
  81.         for (j = i - n - 1; j < i; j++)
  82.             printf("%s\n", s[j]);
  83.  
  84.     fclose(f);
  85.     return 0;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement