In C, files are handled using the standard library functions in `
fopen()
β Open a filefclose()
β Close a filefprintf()
β Write to a filefscanf()
β Read from a file
fopen()
β Opening FilesThe fopen()
function is used to open a file. The syntax for opening a file is as follows:
FILE *fopen(const char *filename, const char *mode);
The mode
argument specifies the mode of access: "r" for reading, "w" for writing, "a" for appending, etc.
fopen()
#includeint main() { FILE *file = fopen("example.txt", "w"); // Open file for writing if (file == NULL) { printf("Failed to open file.\n"); return 1; } fprintf(file, "Hello, World!\n"); // Write to the file fclose(file); // Close the file return 0; }
fclose()
.
fprintf()
β Writing to a FileThe fprintf()
function writes formatted text to a file, similar to printf()
but with the file as the destination.
int fprintf(FILE *stream, const char *format, ...);
fprintf()
#includeint main() { FILE *file = fopen("data.txt", "w"); // Open file for writing if (file == NULL) { printf("Failed to open file.\n"); return 1; } fprintf(file, "Name: John\nAge: 25\nCity: New York\n"); // Write to the file fclose(file); // Close the file return 0; }
fprintf()
function writes multiple lines to the file "data.txt" with formatted data.
fscanf()
β Reading from a FileThe fscanf()
function is used to read formatted input from a file, similar to scanf()
but from a file instead of the console.
int fscanf(FILE *stream, const char *format, ...);
fscanf()
#includeint main() { FILE *file = fopen("data.txt", "r"); // Open file for reading if (file == NULL) { printf("Failed to open file.\n"); return 1; } char name[50]; int age; char city[50]; fscanf(file, "Name: %s\nAge: %d\nCity: %s\n", name, &age, city); // Read data from the file printf("Name: %s\nAge: %d\nCity: %s\n", name, age, city); // Output data fclose(file); // Close the file return 0; }
fscanf()
function reads the contents of the file "data.txt" and stores them in variables name
, age
, and city
.
fclose()
β Closing a FileAfter completing file operations, itβs important to close the file using the fclose()
function. This ensures that resources are freed and no data is lost.
int fclose(FILE *stream);
fclose()
#includeint main() { FILE *file = fopen("example.txt", "w"); if (file == NULL) { printf("Failed to open file.\n"); return 1; } fprintf(file, "This file will now be closed."); fclose(file); // Close the file printf("File closed successfully.\n"); return 0; }
fclose()
to close it and free up system resources.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!