This code will print the contents of a file to the terminal. Feel free to use this in your own projects if you wish.
#include <stdio.h> #define MEM "/proc/diskstats" int main (void) { FILE *g; char Meminfo[40]; g = fopen(MEM, "r"); if(!g) { printf ("Sorry, I cannot open: %s.\n", MEM); } else { while (feof(g) != 1) { fgets(Meminfo, 2, g); printf("%s", Meminfo ); } fflush(stdout); } fclose(g); } |
This code is very fast and useful for opening a text file and reading the contents.
This is how to open a file in C and then append text to it on a new line.
#include <stdlib.h> #include <stdio.h> int main(void) { FILE *f; char buf[256]; f = fopen("logfile", "a+"); if(f) { fprintf(f, "This is appended to the file.\n"); } fclose(f); return 0; } |
If the program uses this line instead, the file will be overwritten with a new line on line 1.
f = fopen("logfile", "w+"); |
That is the difference between appending and overwriting.
1 thought on “C code that will open a file and print the contents to the terminal.”