Welcome to our deep dive into the world of C Programming! Today, we're going to explore File I/O basics - an essential skill for every C programmer. By the end of this lesson, you'll be able to read and write files in your C programs. 📝
File I/O (Input/Output) is a method of reading data from files and writing data into files using C language. It allows C programs to interact with external data sources such as text files, images, and more.
File I/O is crucial because it enables us to store and retrieve data permanently. Unlike variables, which are lost once the program ends, files can be used to save and load data between program sessions. This makes it possible to build more robust and feature-rich applications.
The C Standard Library provides several functions for performing File I/O. The most commonly used are:
#include <stdio.h> - Standard Input/Output libraryFILE *fp; - A pointer to a FILE structurefopen() - Opens a file and returns a FILE pointerfclose() - Closes a file and deallocates the FILE structurefprintf() - Writes formatted data to a filefscanf() - Reads formatted data from a fileLet's write a simple program to read a text file line by line.
#include <stdio.h>
int main() {
FILE *fp = fopen("example.txt", "r"); // Open the file "example.txt" in read mode
if (fp == NULL) {
printf("Error: Unable to open file.\n");
return 1;
}
char line[100];
while (fgets(line, sizeof(line), fp)) {
printf("%s", line);
}
fclose(fp); // Close the file
return 0;
}In this example, we open a file named example.txt in read mode, read the file line by line using fgets(), and print each line to the console.
Now, let's write a simple program to write data to a file.
#include <stdio.h>
int main() {
FILE *fp = fopen("output.txt", "w"); // Open the file "output.txt" in write mode
if (fp == NULL) {
printf("Error: Unable to open file.\n");
return 1;
}
fprintf(fp, "Hello, World!\n"); // Write "Hello, World!\n" to the file
fprintf(fp, "This is a test.\n"); // Write "This is a test.\n" to the file
fclose(fp); // Close the file
return 0;
}In this example, we open a file named output.txt in write mode, write two lines to the file using fprintf(), and close the file.
What library do we include for C File I/O?
That's all for today! In the next lesson, we'll dive deeper into File I/O by discussing more advanced topics like handling errors, reading and writing binary files, and more. Until then, happy coding! 🚀