|
CS456 - Systems Programming
Spring 2026
|
Displaying ./code/h1/head_simple.c
/*
head_simple.c - a simple implementation of the head command in linux
this takes a file through the command line and prints a specified number of
lines from the beginning of the file
if no number is specified, print 10 lines by default.
running below would print the first 10 lines of file (argc = 2)
>./head_simple file
but running below would print the first 18 lines of file (argc = 3)
>./head_simple file 18
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h> //needed for perror
int main(int argc, char **argv){
//check if file was provided , otherwise print usage statement and exit
if(argc < 2){
fprintf(stderr, "Usage: %s file <optional number>\n", argv[0]);
exit(1);
}
//read in a file from the command line using fopen
FILE *fp = fopen(argv[1], "r");
// checking return value of fopen
// if fopen returns NULL, then it failed, so print error message and exit
if(fp == NULL){
perror("open");
exit(-1);
}
//declaring a variable to store the number of lines specified in command line
int numlines;
//if there was a number provided on the command line
//convert that string to an integer and assign it to numlines,
// if not, set numlines to 10
if(argc == 3)
numlines = atoi(argv[2]);
else
numlines = 10;
int c; //fgetc returns an int, hence declaring c as an int
int lines = 0; //keep a count of newline characters encountered so far
//loop through entire file
while((c =fgetc(fp))!= EOF){
//print the character one at a time
//these two lines do the same thing (leave one commented out)
//printf("%c", c); //print the character one at a time
fputc(c, stdout);
//check 'c' for a newline
//if yes, increment count
// if we reach the specified number of lines, break loop
if(c == '\n')
lines++;
if(lines == numlines)
break;
}
fclose(fp); //closing the file as we're done with it
return 0;
}
|