C Programming: File I/O Basics 🎯

beginner
11 min

C Programming: File I/O Basics 🎯

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. 📝

What is File I/O? 💡

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.

Why is File I/O Important? 📝

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.

C Standard Library for File I/O ✅

The C Standard Library provides several functions for performing File I/O. The most commonly used are:

  • #include <stdio.h> - Standard Input/Output library
  • FILE *fp; - A pointer to a FILE structure
  • fopen() - Opens a file and returns a FILE pointer
  • fclose() - Closes a file and deallocates the FILE structure
  • fprintf() - Writes formatted data to a file
  • fscanf() - Reads formatted data from a file

Reading a File 📝

Let's write a simple program to read a text file line by line.

c
#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.

Writing to a File 📝

Now, let's write a simple program to write data to a file.

c
#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.

Quiz 💡

Quick Quiz
Question 1 of 1

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! 🚀