Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- /*
- Too Long Didn't Read program.
- Let n = int(argv[2]);
- This program will print the first and the last n lines of a file
- Might sound simple, but might help somebody.
- */
- int main(int argc, char* argv[]){
- //check arguments
- if(argc > 3){
- printf("Too much argumets\nsyntax: tldr file.ext inser_natural_number_here\n");
- return 1;
- }
- if(argc < 3){
- printf("Too few argumets\nsyntax: tldr file.ext inser_natural_number_here\n");
- return 1;
- }
- //open file
- FILE *fp;
- if((fp = fopen(argv[1], "r")) == NULL){
- printf("Error opening file\n");
- return 1;
- }
- else{
- int c, i, j;
- //Count how many new line are there in the file.
- for(c = i = j = 0; (c = getc(fp)) != EOF && c != '\0';)
- if(c == '\n')
- j++;
- //What if user asks more than there is?
- if((atoi(argv[2])) > j){
- printf("File has only %d lines, you asked for %d, just open the file normally\n", j, atoi(argv[2]));
- return 1;
- }
- //Since I am still not comfortable with fsetpos. I just reset the index.
- if((fp = fopen(argv[1], "r")) == NULL){
- printf("Error opening file\n");
- return 1;
- }
- //Print the first n lines.
- for(c = i = 0; i < atoi(argv[2]);){
- c = getc(fp);
- putchar(c);
- if(c == '\n')
- i++;
- }
- //increment index i until it's at the start of the last n lines.
- for(i = i; i < (j-atoi(argv[2]));){
- if((c = getc(fp)) == '\n')
- i++;
- }
- //Print them.
- while((c = getc(fp)) != EOF)
- putchar(c);
- }
- fclose(fp);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment