Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #define MAX_INPUT_SIZE 100
- #define MAX_STR_LEN 100
- #define DEFAULT_N 10
- void printHelpAndQuit()
- {
- printf("This little useful program can print the last N lines of your input!\n");
- printf("-n\tspecify number of lines to print (%d by default)\n", DEFAULT_N);
- printf("-f\tspecify the file to read from\n");
- printf("-h\tprint this message\n");
- exit(0);
- }
- int main(int argc, char const *argv[])
- {
- char s[MAX_INPUT_SIZE][MAX_STR_LEN];
- int n = 10, i = 0, j = 0;
- FILE *f = stdin;
- for (i = 1; i < argc; i++)
- {
- if (strcmp(argv[i], "-f") == 0)
- {
- // Read from file
- if (i + 1 < argc)
- {
- //Try open file
- if ((f = fopen(argv[++i], "r")) == NULL)
- {
- printf("Error: Can not read file\n");
- printHelpAndQuit();
- }
- }
- else
- {
- printf("Error: Specify file name\n");
- printHelpAndQuit();
- }
- }
- else if (strcmp(argv[i], "-n") == 0)
- {
- //Redefine number of lines to print
- if (i + 1 < argc)
- {
- char *pEnd;
- n = strtol(argv[i + 1], &pEnd, 10);
- if (pEnd == argv[i + 1])
- {
- printf("Error: Argument -n is not valid number\n");
- printHelpAndQuit();
- }
- i++;
- }
- else
- {
- printf("Error: Specify number of lines to print after -n\n");
- printHelpAndQuit();
- }
- }
- else if (strcmp(argv[i], "-h") == 0)
- {
- printHelpAndQuit();
- }
- else
- {
- printf("Invalid parameter\n");
- printHelpAndQuit();
- }
- }
- i = 0;
- while (fscanf(f, "%s", s[i++]) != EOF);
- printf("\n");
- if (n > i - 1)
- printf("Too many lines to print!\n");
- else
- for (j = i - n - 1; j < i; j++)
- printf("%s\n", s[j]);
- fclose(f);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement