logoISU  

CS456 - Systems Programming

Spring 2023

Displaying ./code/commands/cat.c

/*

implementing a version of the "cat" command

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

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

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


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

	//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 then will read every character in the file, and then print it to the screen
	char c;

	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

	}

	fclose(fd); //close the file

	return 0;

}