C program that extends my.c to take file names as command line arguments. It will read each named file and write the first 10 lines to standard output. If there are no command line arguments, it will read from standard input. If "-" is given as a file name, it will read from standard input.

As with the Linux version of head, program should print the file name (or standard input) if there are two or more command line arguments. Use the same format as the Linux version of head.

Write a function void do_file(FILE *infile) that takes a stream and processes that stream, open the files in main and call do_file to process them.

Check to make sure that files open properly and print appropriate error messages to stderr (in the usual Unix style - using errno) if not. If a file cannot be opened, go ahead and process the other files.

My my.c Code is here:

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

void do_file(FILE * infile){

  int lineCount = 0; // keeps track of lines                                                                                                                                         
  char line [128];

  // read file line by line                                                                                                                                                          
  while(fgets(line, 128, infile) != NULL){
    lineCount++;
    if(lineCount <= 10)
      fputs(line, stdout); // write line to stdout                                                                                                                                   
  }
}

int main(int argc, char * argv[]){

  do_file(stdin);
  return 0;
}

Thanks.

OK, and what was your question?

EDIT: The rest of this was incorrect; I had overlooked the fact that fgets() stops at newlines. Please disregard.

Edited 3 Years Ago by Schol-R-LEA

How to check for the file name, If there are no command line arguments, it will read from standard input. If "-" is given as a file name, it will read from standard input. As with the Linux version of head, program should print the file name (or standard input) if there are two or more command line arguments. Use the same format as the Linux version of head.

This question has already been answered. Start a new discussion instead.