Guest User

Untitled

a guest
Nov 7th, 2026
22
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.51 KB | Source Code | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. /*
  5.     Too Long Didn't Read program.
  6.     Let n = int(argv[2]);
  7.     This program will print the first and the last n lines of a file
  8.  
  9.     Might sound simple, but might help somebody.
  10. */
  11. int main(int argc, char* argv[]){
  12.  
  13. //check arguments
  14.     if(argc > 3){
  15.         printf("Too much argumets\nsyntax: tldr file.ext inser_natural_number_here\n");
  16.         return 1;
  17.     }
  18.     if(argc < 3){
  19.         printf("Too few argumets\nsyntax: tldr file.ext inser_natural_number_here\n");
  20.         return 1;
  21.     }
  22.  
  23. //open file
  24.     FILE *fp;
  25.     if((fp = fopen(argv[1], "r")) ==  NULL){
  26.         printf("Error opening file\n");
  27.         return 1;
  28.     }
  29.     else{
  30.         int c, i, j;
  31.     //Count how many new line are there in the file.
  32.         for(c = i = j = 0; (c = getc(fp)) != EOF && c != '\0';)
  33.             if(c == '\n')
  34.                 j++;
  35.     //What if user asks more than there is?
  36.         if((atoi(argv[2])) > j){
  37.             printf("File has only %d lines, you asked for %d, just open the file normally\n", j, atoi(argv[2]));
  38.             return 1;
  39.         }
  40.     //Since I am still not comfortable with fsetpos. I just reset the index.
  41.         if((fp = fopen(argv[1], "r")) ==  NULL){
  42.             printf("Error opening file\n");
  43.             return 1;
  44.         }
  45.     //Print the first n lines.
  46.         for(c = i = 0; i < atoi(argv[2]);){
  47.             c = getc(fp);
  48.             putchar(c);
  49.             if(c == '\n')
  50.                 i++;
  51.         }
  52.     //increment index i until it's at the start of the last n lines.
  53.         for(i = i; i < (j-atoi(argv[2]));){
  54.             if((c = getc(fp)) == '\n')
  55.                 i++;
  56.         }
  57.     //Print them.
  58.         while((c = getc(fp)) != EOF)
  59.             putchar(c);
  60.     }
  61.     fclose(fp);
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment