C File Handling
File handling is an essential aspect for reading from and writing to files.
The standard I/O (<stdio.h>) library provides functions for file operations.
Get a detailed use of functions and its uses below;
The standard I/O (<stdio.h>) library provides functions for file operations.
Get a detailed use of functions and its uses below;
Operation
Function
Description
Opening a File
fopen
Opens a file for specified operations (r, w, a, etc.)
Reading from a File
fscanf, fgetc
Reads data from a file using specified formats or characters
Writing to a File
fprintf, fputc
Writes data to a file using specified formats or characters
Reading Characters
fgetc
Reads a single character from a file
Writing Characters
fputc
Writes a single character to a file
Reading Strings
fscanf, fgets
Reads strings from a file using specified formats or lines
Writing Strings
fprintf, fputs
Writes strings to a file using specified formats or lines
Checking for EOF
feof
Checks if the end of file has been reached
Closing a File
fclose
Closes a previously opened file
Example
#include <stdio.h>
int main() {
FILE *fptr; // File pointer
char text[100]; // Buffer for reading/writing
// Opening a file for writing
fptr = fopen("example.txt", "w");
if (fptr == NULL) {
printf("Error opening the file for writing.\n");
return 1; // Return an error code
}
// Writing to the file
fprintf(fptr, "Hello, World!\n");
fprintf(fptr, "This is a C file handling example.");
// Closing the file after writing
fclose(fptr);
// Opening the same file for reading
fptr = fopen("example.txt", "r");
if (fptr == NULL) {
printf("Error opening the file for reading.\n");
return 1; // Return an error code
}
// Reading from the file and printing to the console
printf("Content of the file:\n");
while (fgets(text, sizeof(text), fptr) != NULL) {
printf("%s", text);
}
// Closing the file after reading
fclose(fptr);
return 0; // Return success code
}
Quick Recap
Topics Covered
C File Handling
Practice With Examples in Compilers
The Concepts and codes you leart practice in Compilers till you are confident of doing on your own. A Various methods of examples, concepts, codes availble in our websites. Don't know where to start Down some code examples are given for this page topic use the code and compile
Example 1
Example 1
Example 2
Example 3
Example 4
Example 5