C File Operations – Open, Close, Read & Write Files
In C, file operations allow you to perform tasks like opening, reading, writing, and closing files. You use file pointers and various standard functions from <stdio.h>
.
๐น fopen() and fclose()
fopen()
is used to open a file, and fclose()
is used to close it. Always close a file after use.
๐ Example: Open and Close File
#include <stdio.h> int main() { FILE *fp = fopen("demo.txt", "w"); if (fp == NULL) { printf("Unable to open file!\n"); return 1; } fprintf(fp, "Hello, file operations in C!\n"); fclose(fp); printf("File written and closed successfully.\n"); return 0; }
๐น fputc() and fgetc()
fputc()
writes a single character to a file, and fgetc()
reads a character from a file.
๐ Example: Write and Read Characters
#include <stdio.h> int main() { FILE *fp; // Writing to file fp = fopen("letters.txt", "w"); fputc('A', fp); fputc('B', fp); fclose(fp); // Reading from file fp = fopen("letters.txt", "r"); char ch; while ((ch = fgetc(fp)) != EOF) { printf("Char read: %c\n", ch); } fclose(fp); return 0; }
๐น feof() – Detecting End of File
The feof()
function returns true when the end of a file is reached.
๐ Example: Using feof()
#include <stdio.h> int main() { FILE *fp = fopen("letters.txt", "r"); char ch; if (fp == NULL) { printf("File not found!\n"); return 1; } while (!feof(fp)) { ch = fgetc(fp); if (ch != EOF) printf("%c ", ch); } fclose(fp); return 0; }
๐ฏ Summary of File Functions
fopen()
โ Opens a filefclose()
โ Closes a filefputc()
โ Writes a characterfgetc()
โ Reads a characterfeof()
โ Checks end-of-file
๐ก Practice Challenge
Create a file, write a few characters using fputc()
, then reopen it and read using fgetc()
. Try adding your name letter-by-letter!