Ad space (banner)
๐Ÿ”งC Lessons
Lesson 52 / 68

File Reading and Writing Basics

This lesson covers the basics of reading and writing files in C, so a program can save and load a text file. It's for anyone searching "C fopen fprintf usage."

fopen() opens a file, fprintf() writes to it, and fgets() reads from it. You always need to close it with fclose() once you're done. A basic operation used constantly in real work โ€” saving a config file or a log, for example.

The example opens a file in write mode with fopen("memo.txt", "w"), writes content with fprintf(), closes it with fclose(), then reopens it in read mode with fopen("memo.txt", "r") to read it back line by line with fgets().

A common early mistake is forgetting to call fclose(). Leave a file open without closing it, and data might not get written correctly, or it can cause a resource leak.

In real projects, reliably following the open-use-close sequence every time you work with a file is a basic C programming convention.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)