0
0
Cprogramming~30 mins

Writing to files in C - Mini Project: Build & Apply

Choose your learning style9 modes available
Writing to files
📖 Scenario: Imagine you want to save a list of your favorite fruits to a file on your computer so you can look at it later or share it with friends.
🎯 Goal: You will write a simple C program that creates a file and writes a list of fruits into it, one fruit per line.
📋 What You'll Learn
Create an array of strings with exact fruit names
Open a file for writing with the exact filename
Write each fruit to the file on its own line
Close the file properly
Print a confirmation message after writing
💡 Why This Matters
🌍 Real World
Saving data to files is common in many programs, like saving user preferences, logs, or reports.
💼 Career
Understanding file writing is essential for software developers working on data storage, configuration files, or any program that needs to save information.
Progress0 / 4 steps
1
Create the fruit list
Create a string array called fruits with these exact entries: "Apple", "Banana", "Cherry", "Date", "Elderberry".
C
Need a hint?

Use char *fruits[] = { ... }; to create the array of fruit names.

2
Open the file for writing
Add a variable called file of type FILE * and open a file named "fruits.txt" for writing using fopen.
C
Need a hint?

Use FILE *file = fopen("fruits.txt", "w"); to open the file for writing.

3
Write fruits to the file
Use a for loop with an integer variable i from 0 to 4 to write each fruit from fruits[i] to the file using fprintf, adding a newline after each fruit.
C
Need a hint?

Use for (int i = 0; i < 5; i++) and inside the loop fprintf(file, "%s\n", fruits[i]);.

4
Close the file and print confirmation
Close the file using fclose(file) and then print "Fruits saved to fruits.txt" using printf. End the main function with return 0;.
C
Need a hint?

Use fclose(file); to close the file and printf("Fruits saved to fruits.txt\n"); to print the message.