Read in a file and print to stdout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
int main(void){ | |
// I have a file with the following text: | |
/* | |
There lived a man named Jerry, | |
He was super duper merry. | |
He jumped and danced, | |
He banged on cans, | |
The happiest man named Jerry. | |
*/ | |
// Let's grab this file and print the entire | |
// poem into the terminal | |
// first let's take our file pointer and get | |
// our file using fopen in one slick line | |
// we have to be in read mode ("r") | |
FILE * fp = fopen("poem.txt", "r"); | |
// we can pull in one character at a time using fgetc() | |
// and we will know when to stop once feof() is true | |
// each time fgetc() is called the index is automagically incremented | |
// which is why it goes to the next character without us being involved | |
char c; | |
while(1){ | |
if(feof(fp)) | |
break; | |
c = fgetc(fp); | |
printf("%c", c); | |
} | |
printf("\n"); | |
fclose(fp); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment