Welcome to our comprehensive guide on C File I/O! In this tutorial, we'll delve into the world of file handling in C, a crucial aspect of programming that allows you to read, write, and manipulate files. Let's get started! 🎯
File Input/Output (I/O) refers to the way a computer program reads data from a file and writes data to a file. In C, you can perform various operations like reading from a file, writing to a file, appending to a file, and more.
File I/O is essential for data persistence and working with large datasets. It allows programs to read and write data to files, making it easier to store and manage data even after the program has ended.
To read from a file in C, you'll use the fopen(), fgets(), and fclose() functions. Here's a simple example:
#include <stdio.h>
int main() {
FILE *fp;
char filename[] = "example.txt";
char buffer[100];
fp = fopen(filename, "r"); // Open the file in read mode
if(fp == NULL) {
printf("Error: Unable to open file.\n");
return 1;
}
while(fgets(buffer, sizeof(buffer), fp) != NULL) {
printf("Content: %s", buffer);
}
fclose(fp); // Close the file
return 0;
}In this example, we open a file named example.txt for reading. We then read the file line by line using fgets() and print each line.
Writing to a file in C involves the fopen(), fprintf(), and fclose() functions. Here's a simple example:
#include <stdio.h>
int main() {
FILE *fp;
char filename[] = "example.txt";
fp = fopen(filename, "w"); // Open the file in write mode
if(fp == NULL) {
printf("Error: Unable to create file.\n");
return 1;
}
fprintf(fp, "Hello, World!"); // Write to the file
fclose(fp); // Close the file
return 0;
}In this example, we open a file named example.txt for writing. We then write the string "Hello, World!" to the file.
What function is used to open a file in C?
That's it for this introduction to C File I/O! In the next lessons, we'll dive deeper into more advanced topics like handling errors, reading and writing binary files, and more. Stay tuned! 🎯