C Programming: Writing to a File 📝

beginner
16 min

C Programming: Writing to a File 📝

Welcome to our in-depth lesson on C Programming: Writing to a File! In this tutorial, we will guide you through the process of writing data to a file using C programming. Let's dive in! 🎯

Understanding Files in C 📝

Before we start writing to a file, let's understand what a file is in C programming:

  • A file is a collection of data stored on your computer.
  • In C, files are handled as streams.
  • There are two types of streams: stdin (standard input) and stdout (standard output).
  • To write to a file, we need a third stream called stdout.

Opening a File in C 📝

To write to a file, we first need to open it using the fopen() function:

c
FILE *filePtr; filePtr = fopen("example.txt", "w");

Here's what's happening:

  1. FILE *filePtr; declares a variable filePtr of type FILE.
  2. fopen("example.txt", "w") opens a file named example.txt in write mode ("w").

Pro Tip: 💡

Make sure the file does not exist before you open it in write mode, as it will overwrite any existing data.

Writing to a File in C 📝

Once the file is open, we can write to it using the fprintf() function:

c
fprintf(filePtr, "Hello, World!\n");

Here's what's happening:

  1. fprintf(filePtr, "Hello, World!\n") writes "Hello, World!" (including the newline character \n) to the file pointed by filePtr.

Closing a File in C 📝

After writing to the file, we must close it using the fclose() function:

c
fclose(filePtr);

Here's what's happening:

  1. fclose(filePtr) closes the file pointed by filePtr.

Example Program 📝

Here's a complete example program that writes "Hello, World!" to a file named example.txt:

c
#include <stdio.h> int main() { FILE *filePtr; filePtr = fopen("example.txt", "w"); if (filePtr == NULL) { printf("Error: Could not open file.\n"); return 1; } fprintf(filePtr, "Hello, World!\n"); fclose(filePtr); printf("Successfully wrote to file.\n"); return 0; }

In this program, we first check if the file can be opened. If it can't, we print an error message and exit. If the file can be opened, we write "Hello, World!" to it and then close it.

Reading from a File 📝

Now that you know how to write to a file, let's learn how to read from a file in our next lesson! 🎯

Quiz 📝

Question: What does fopen("example.txt", "w") do in C programming?

A: Opens a file named example.txt in read mode B: Opens a file named example.txt in write mode C: Opens a file named example.txt in append mode

Correct: B Explanation: The fopen("example.txt", "w") function opens a file named example.txt in write mode, which allows us to write data to the file.