Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C language Program myhead.c – Write a program that simply reads the first N line

ID: 3885252 • Letter: C

Question

C language Program

myhead.c – Write a program that simply reads the first N lines(default 10 lines) of an ASCII file and displays it on the terminal (stdout). Note: there is already a program called ‘head’. The pgram should optimally take one argument, which changes the default number of lines.

% myhead <-n> filename

for examples

% ./myhead myhead.c

% ./myhead -5 myhead.c

“-5” means only display the first 5 lines. “-” is called a “switch”, and is an argument to the program.

In general, do NOT use any section 3 I/O library calls (no “stdoi” calls), except for error handling. Please do use perror(3). System calls used should be confined to open (2), close(2), read(2) and write(2) or any other section 2 calls you might want. In order to write to stdout, you can use convention: write(1, buf, cc).

Check all system calls for errors, print an error message with perror(3) if a system call fails andn then call exit(1).

Note: as a test, we will expect that “% ./myhead -5 /dev/tty” will work as expected; i.e.: the program should be able to read input from stdin.

Explanation / Answer

#include<stdio.h>
#include<stdlib.h>

int main(int argc, char **argv){
  
    FILE *fp;
    char *line = NULL;
    size_t len = 0;
    ssize_t read;
    int count;

    fp = fopen(argv[2],"r");
    if (fp == NULL)
       return 0;
    count = 0;
   
    while ((read = getline(&line, &len, fp)) != -1 && count < atoi(argv[1]))
    {
          printf("%s ",line);
          count++;
    }
    fclose(fp);
    return 0;
}