Home » C solved programs » C file handling programs

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.

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.





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.