Skip to content

Instantly share code, notes, and snippets.

@sojohnnysaid
Last active January 19, 2021 22:54
Show Gist options
  • Save sojohnnysaid/e3785b177fb0bf20031593979922755c to your computer and use it in GitHub Desktop.
Save sojohnnysaid/e3785b177fb0bf20031593979922755c to your computer and use it in GitHub Desktop.
Read in a file and print to stdout
#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