In: Computer Science
C Programming
Number output lines of a text file as it prints to the terminal
Do not use fgets or fopen
It is possible to open file without fopen using SyS commands such as open and RDONLY
Example
1 Line 1
2 Line2
The C program to print the lines of the text file to the terminal are given as follows:
Code:
#include <stdio.h> int main(int argc, char * argv[]) { FILE * fp; // file pointer char * line = NULL; int len = 0; int cnt = 0; if( argc < 3) { printf("Insufficient Arguments!!!\n"); printf("Please use \"program-name file-name N\" format.\n"); return -1; } // open file fp = fopen(argv[1],"r"); // checking for file is exist or not if( fp == NULL ) { printf("\n%s file can not be opened !!!\n",argv[1]); return 1; } // read lines from file one by one while (getline(&line, &len, fp) != -1) { cnt++; if ( cnt > atoi(argv[2]) ) break; printf("%s",line); fflush(stdout); } // close file fclose(fp); return 0; }
Code in running:
So,
the code prints the output of the number of the lines in the
file.
-----------------------------------------------------Please Upvote--------------------------------------------------------------------------