C File I/O Basics – Read and Write Files in C
In C programming, file I/O allows your program to read from and write to files on disk. This is essential for storing data permanently beyond program execution.
๐ฆ File I/O Functions
fopen()
– Open a filefprintf()
/fscanf()
– Write/read formatted datafclose()
– Close a filefgets()
/fputs()
– Read/write strings
๐ Example: Write to a File
This example writes text to a file called output.txt
.
#include <stdio.h> int main() { FILE *fp = fopen("output.txt", "w"); // Open file for writing if (fp == NULL) { printf("Error opening file!\n"); return 1; } fprintf(fp, "Hello, file I/O in C!\n"); fclose(fp); // Always close the file printf("Data written to file successfully.\n"); return 0; }
๐ Example: Read from a File
This reads and prints content from output.txt
.
#include <stdio.h> int main() { char buffer[100]; FILE *fp = fopen("output.txt", "r"); // Open file for reading if (fp == NULL) { printf("File not found!\n"); return 1; } while (fgets(buffer, sizeof(buffer), fp) != NULL) { printf("%s", buffer); // Print each line } fclose(fp); return 0; }
๐ File Modes in fopen()
Mode | Description |
---|---|
“r” | Open file for reading |
“w” | Create file for writing (overwrite if exists) |
“a” | Append to file (create if not exists) |
“r+” | Read and write |
“w+” | Read and write (overwrite) |
“a+” | Read and append |
๐ฏ Practice Tip
Try creating your own file, writing different data types using fprintf
, and then reading them back. Remember to always close your files with fclose()
! ๐๏ธ