Basic File Handling in C


Introduction

File handling is an essential part of C programming. It allows you to read data from files, write data to files, and manipulate file contents. In this guide, we'll explore the basics of file handling in C, including functions like fopen(), fread(), fwrite(), and provide sample code to demonstrate their usage.


Opening and Closing Files

To work with files in C, you must first open them using fopen() and close them when you're done with fclose(). Here's an example:

#include <stdio.h>
int main() {
FILE *file;
file = fopen("sample.txt", "w"); // Open for writing
if (file == NULL) {
printf("File could not be opened.\\n");
return 1;
}
// Your file operations here
fclose(file); // Close the file
return 0;
}

In this example, we open a file named "sample.txt" for writing using the fopen() function. We check if the file was opened successfully, and if not, we display an error message. Finally, we close the file using fclose() when we're done with it.


Writing to Files

You can write data to a file using the fwrite() function:

#include <stdio.h>
int main() {
FILE *file;
file = fopen("sample.txt", "w");
if (file == NULL) {
printf("File could not be opened.\\n");
return 1;
}
char text[] = "Hello, World!";
fwrite(text, sizeof(char), sizeof(text), file);
fclose(file);
return 0;
}

In this example, we open the file "sample.txt" for writing and then use fwrite() to write the "Hello, World!" text to the file.


Reading from Files

You can read data from a file using the fread() function:

#include <stdio.h>
int main() {
FILE *file;
file = fopen("sample.txt", "r");
if (file == NULL) {
printf("File could not be opened.\\n");
return 1;
}
char text[100];
fread(text, sizeof(char), sizeof(text), file);
printf("Read from file: %s\\n", text);
fclose(file);
return 0;
}

In this example, we open the file "sample.txt" for reading and then use fread() to read text from the file and display it.


Conclusion

File handling is a crucial part of C programming, allowing you to work with external data storage. This guide has introduced you to the basics of file handling, including opening, closing, reading, and writing to files. As you continue your journey in C programming, you'll discover the power and flexibility of file operations for various tasks.