logoISU  

CS256 - Principles of Structured Design

Fall 2021

Displaying ./code/cs256su21code/jun30/readFile.c

/*

reading an external file via command line argument
and outputting the contents

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


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

	/* 
		the below code is so if the user enters just the name of the executable, then we just
		print a usage statement and then exits the program.

	*/
	if(argc < 2){
		printf("Usage %s file\n", argv[0]);
		exit(1);
	}
	/* 
		the function "exit" is like the return keyword, execpt it exits the entire
        program. the number inside the parenthesis is just what status value you want 
        returned to the operating system. you can put whatever number you need in here.

        you will need to include stdlib.h in order to use this function.
    */ 

	char buffer[1024];

	FILE *fp; 
	/*
	 you declare a file pointer using the datatype FILE. all file variables will need pointers in order
	 to access the file, so every single variable using the datatype FILE needs to have the * in front 
	 of the variable name.
	*/

	fp = fopen(argv[1], "r");

	/*
		fopen function opens the file for our program to use.

		this function takes two arguments: 
		-the filename: (which, in ths case is stored in argv[1])
		-the mode: one of three modes 
					"r" - reading
					"w" - writing
					"a" - appending (like w, but starts at the end of the file)

		in "r" mode, it is important to check the return value of the function to prevent crashing, hence
		the if statement below. in "w" and "a" modes, if the file doesn't exist it will create the file

	*/

	if(fp == NULL){
		printf("Cannot open file\n");
		exit(-1);
	}

	//printf("File %s successfully opened.\n", argv[1]);

	while(fgets(buffer, 1024, fp) != NULL){ //now just looping through the file, printing each line as a string

		printf("%s", buffer);

	}


	fclose(fp); // before ending the program, make sure you use fclose to close the file.

	return 0;
}