Q:

C program to print given number of lines of a file (like head command in Linux)

0

C program to print given number of lines of a file (like head command in Linux)

This program will print the given number of lines of a file, just like Head command in Linux. Head command displays only the given number of lines of a given file name. Same as head command in this program you have to supply file name then number of lines.
The syntax of executing this program
./program-name file-name N
Here N is the number of lines, if available lines in the file are less than N, program will display all lines of the file.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

C program to print given number of lines of a file

linux head command implementation

//c program to print given number of lines from beginning of a file
//file name and number of lines must be supply as command line argument
 
#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;
}

Output

First Run:
Terminal command : ./prg1 file1.txt
Insufficient Arguments!!!
Please use "program-name file-name N" format.

Second Run:
Terminal command : ./prg1 file1.txt 5
this is line 1.
this is line 2.
this is line 3.
this is line 4.
this is line 5.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

File Handling Examples Programs in C language

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to print contents in reverse order of a ... >>
<< C program to create, write and read text in/from f...