0
0
Cprogramming~15 mins

Opening and closing files - Mini Project: Build & Apply

Choose your learning style9 modes available
Opening and closing files
📖 Scenario: You are creating a simple program to read data from a text file. Before you can read the data, you need to open the file safely and then close it when done.
🎯 Goal: Build a C program that opens a file called data.txt in read mode, checks if the file opened successfully, and then closes the file.
📋 What You'll Learn
Create a FILE* pointer variable named file.
Open the file data.txt in read mode using fopen.
Check if the file opened successfully by testing if file is not NULL.
Close the file using fclose.
Print "File opened and closed successfully." if the file opens, otherwise print "Failed to open file.".
💡 Why This Matters
🌍 Real World
Opening and closing files is a basic task in many programs that need to read or write data, such as reading configuration files or saving user data.
💼 Career
Understanding file handling is essential for software developers, especially those working with system programming, data processing, or embedded systems.
Progress0 / 4 steps
1
Create a FILE* pointer variable
Create a FILE* pointer variable called file and set it to NULL.
C
Need a hint?

Use FILE *file = NULL; to declare the file pointer.

2
Open the file data.txt in read mode
Use fopen to open the file "data.txt" in read mode "r" and assign it to the variable file.
C
Need a hint?

Use file = fopen("data.txt", "r"); to open the file.

3
Check if the file opened successfully
Write an if statement to check if file is not NULL. If it is not NULL, print "File opened and closed successfully.". Otherwise, print "Failed to open file.".
C
Need a hint?

Use if (file != NULL) to check if the file opened.

4
Close the file
Inside the if block where file is not NULL, close the file using fclose(file);.
C
Need a hint?

Use fclose(file); to close the file inside the if block.