logoISU  

CS456 - Systems Programming

Spring 2025

Displaying ./code/h1/myHead.c

/*

implementing a version of the "head" command

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

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

	if(argc < 2){  //prints usage statement if not enough arguments
		fprintf(stderr,"Usage: %s <file> <number of lines>\n", argv[0]);
		exit(1);
	}

	//declares file pointer, tries to open file specified by user
	int lines;
	FILE *fd; 
	fd = fopen(argv[1], "r");


	if(argc < 3){ //only the filename was specified, so use default value
		lines = 10; // sets default value for head, if no argument provided
	} else { // number of lines was specified, so use that value
		lines = atoi(argv[2]);
	}

	//if file does not exist, print usage statement and exit the program
	if(fd == NULL){
		fprintf(stderr, "ERROR: Cannot open %s, file probably does not exist.\n", argv[1]);
		exit(-1);
	}

	// if we get here, we read every character in the file, and then print it to the screen
	char c;
	int linecount = 0;
	while((c=fgetc(fd))){

		if(c == EOF) break; //we've reached the end of file, break the loop
		
		putchar(c); // prints a single character to the screen

		if(c == '\n') linecount++; //we see a newline, so increment linecount

		if(linecount >= lines) break; //we've seen the number of lines specified, so break the loop

	}

	fclose(fd); //close the file

	return 0;

}