logoISU  

CS456 - Systems Programming

Spring 2026

Displaying ./code/jan28/cat_simple.c

// a simple implentation of the cat command

#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\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("fopen");
		exit(-1);
	}	

	int c; //fgetc returns an int, hence declaring c as an int

	//loop through entire file
	while((c =fgetc(fp))!= EOF){
		printf("%c", c); //print the character one at a time

	}	

	
	fclose(fp); //closing the file as we're done with it

	return 0;

}