forked from portfoliocourses/c-example-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdisplay_file_contents.c
39 lines (33 loc) · 1.13 KB
/
display_file_contents.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*******************************************************************************
*
* Program: Print File Contents
*
* Description: Example of reading and printing a file's contents in C.
*
* YouTube Lesson: https://www.youtube.com/watch?v=fLPqn026DaE
*
* Author: Kevin Browne @ https://portfoliocourses.com
*
*******************************************************************************/
#include <stdio.h>
int main()
{
// fh is the file handle we use to access the file
FILE *fh;
// open the file in "read mode"
fh = fopen("file.txt", "r");
// fopen will return NULL if the file wasn't opened successfully, so we
// make sure it has opened OK before accessing the file
if (fh != NULL)
{
// read each character of the file one at a time until end of file (EOF) is
// returned to signify the end of the file, output each char to the console
char c;
while ( (c = fgetc(fh)) != EOF )
putchar(c);
// close the file handle as we are done with the file
fclose(fh);
// if there was a problem opening the file, output an error message
} else printf("Error opening file.\n");
return 0;
}