📖 Scenario: You are creating a simple program to read a list of names from a text file and display them on the screen. This is like opening a guest list and showing each guest's name one by one.
🎯 Goal: Build a C program that opens a file called names.txt, reads each line (each name), and prints all the names to the screen.
📋 What You'll Learn
Open the file names.txt for reading
Read each line from the file using fgets
Print each name to the screen
Close the file after reading
💡 Why This Matters
🌍 Real World
Reading from files is a common task in many programs, such as loading user data, configuration settings, or lists of items.
💼 Career
Understanding file input/output is essential for software developers, especially when working with data files, logs, or user inputs stored in files.
Progress0 / 4 steps
1
Create a file pointer and open the file
Write a line of code to create a file pointer called file and open the file "names.txt" in read mode using fopen.
C
Hint
Use FILE *file = fopen("names.txt", "r"); to open the file for reading.
2
Create a buffer to hold each line
Add a character array called line with size 100 to store each line read from the file.
C
Hint
Declare char line[100]; to hold each name line.
3
Read each line from the file using fgets
Write a while loop that uses fgets(line, 100, file) to read each line until the end of the file.
C
Hint
Use while (fgets(line, 100, file)) to read lines until no more lines are left.
4
Print each line and close the file
Inside the while loop, write printf("%s", line); to print each name. After the loop, close the file using fclose(file);.
C
Hint
Use printf("%s", line); inside the loop and fclose(file); after the loop.
Practice
(1/5)
1. What does the fopen() function with mode "r" do in C?
easy
A. It deletes a file.
B. It opens a file for reading only.
C. It creates a new file.
D. It opens a file for writing only.
Solution
Step 1: Understand fopen modes
The mode "r" in fopen means open the file for reading only.
Step 2: Check other modes
Modes like "w" are for writing, "a" for appending, and none delete files.
Final Answer:
It opens a file for reading only. -> Option B
Quick Check:
fopen with "r" = open for reading [OK]
Hint: Remember: "r" means read only mode in fopen [OK]
Common Mistakes:
Confusing "r" with write mode "w"
Thinking fopen deletes or creates files with "r"
Not checking if file exists before reading
2. Which of the following is the correct way to open a file named data.txt for reading in C?
easy
A. FILE *fp = fopen("data.txt", "r");
B. FILE *fp = fopen("data.txt", "w");
C. FILE *fp = fopen("data.txt", "a");
D. FILE *fp = fopen("data.txt");
Solution
Step 1: Check fopen syntax
fopen requires two arguments: filename and mode as strings.