How to read from a file in C Programming

/*
* Program to read from files
* From the book: C Programming Visual Quickstart Guide
*/


#include <stdio.h>

/*
* Set the file path and name as a C pre-processor
* macro.
*/

#define THEFILE "read_text.txt"

/*
* Begin main function.
*/

int main (void) {

/* 
* Create a file pointer.
*/

FILE *fp;


/*
* Define the required variable. Only one variable is necessary
* for this application (aside from the pointer.) The line 
* character array will store the data retrived from the text
* file. Its length (30) allows for a resonable amount of data,
* based on what we expect the text file to contain.
*/

char line[30]; 

/*
* Open the file for reading. The r mode is used to only read 
* from a file.
*/

fp = fopen(THEFILE, "r");

/* 
* Start a conditional based on the file pointer and print a
* caption. 
*/

if (fp != NULL) {

printf("The contents of the 'read_text.txt' file:\n");

/*
* Read and print the file's contents in a loop.
* This loop will continue to use the fgets()
* function to read in from the file as long as it 
* can (which is until it reaches the file's end.) 
* With each iteration of the loop, the data read with
* fgets() is assigned to a line variable, which is then
* printed as a simple string.
*/

while (fgets(line, sizeof(line), fp)) {

printf("%s", line);

}

/*
* Complete the fp conditional.
*/

} else {

printf("The file could not be opened.\n");

/*
* Exit the function/application.
*/

return 1; 

}

/*
* Close the file.
*/

if (fclose(fp) != 0) {

printf("The file could not be closed.\n");

}

/* 
* Complete the main function.
*/

getchar();
return 0;

}

Leave a Reply

Your email address will not be published. Required fields are marked *