🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

C File Handling — fopen, fread, fwrite, fclose

C FundamentalsC File Handling🟢 Free Lesson

C File Handling — fopen, fread, fwrite, fclose

Learning Objectives

  • Open and close files with correct modes
  • Write and read text data with standard functions
  • Work with binary records using fread and fwrite
  • Check for errors and avoid common file bugs

Why Files Matter

Programs that only live in memory lose everything when they exit. File handling lets your code save results, load settings, process logs, and exchange data with other tools. C provides a small set of stream functions declared in the standard input and output header that work across platforms.

Every file operation follows a similar rhythm: open the file, read or write through a pointer, check for errors, then close the file so buffers flush and operating system resources are released.

Opening and Closing

The fopen function opens a file and returns a pointer to a stream structure, or null on failure. The mode string tells the runtime whether you intend to read, write, or append, and whether the data is text or binary.

#include 

int main(void) {
    FILE *f = fopen("notes.txt", "w");

    if (f == NULL) {
        printf("Could not open the file.\n");
        return 1;
    }

    fprintf(f, "Hello from C\n");
    fclose(f);
    return 0;
}
ModeMeaning
rRead an existing file
wCreate or truncate for writing
aAppend to the end
rb or wbBinary read or write
r plus or w plusUpdate, read and write

The w mode erases existing content. If you only want to add lines, choose append mode so earlier data survives. Always test for null because permission problems or missing directories make open calls fail regularly.

Writing and Reading Text

fprintf works like printf but targets a file stream. fscanf reads formatted text back into variables. fgets and fputs handle whole lines, which often simplifies text processing and avoids some scanning pitfalls.

FILE *f = fopen("scores.txt", "w");
fprintf(f, "Anna 95\n");
fprintf(f, "Ben 88\n");
fclose(f);

FILE *in = fopen("scores.txt", "r");
char name[32];
int score;

if (fscanf(in, "%31s %d", name, &score) == 2) {
    printf("%s scored %d\n", name, score);
}
fclose(in);

Notice the width limit on the string scan, which protects the name buffer. Checking the return value tells you whether both fields were parsed successfully before you trust the variables.

Binary Reading and Writing

Binary mode stores objects exactly as they live in memory, which is compact and fast for fixed-size records. fwrite writes raw bytes from a buffer, and fread reads them back. This approach suits databases, save games, and cached results.

typedef struct {
    int id;
    double amount;
} Record;

Record r = {101, 49.95};
FILE *f = fopen("data.bin", "wb");

fwrite(&r, sizeof(Record), 1, f);
fclose(f);

Record back;
FILE *in = fopen("data.bin", "rb");
fread(&back, sizeof(Record), 1, in);
fclose(in);

printf("%d %.2f\n", back.id, back.amount);

Binary files are not human-readable text editors and may not be portable across machines with different data layouts. For interchange formats, text or a documented serialization approach is often safer.

Error Checking and Closing

Beyond fopen, check the results of fwrite and fread when data integrity matters. A short write often means the disk filled up or the stream hit an error. The feof and ferror helpers report end-of-file and error conditions.

⚠️Always Close Your Files

An unclosed stream may lose buffered data and can exhaust the limited number of files a process may hold open. Pair every successful fopen with a fclose on every path out of the function, including error paths.

Common File Bugs

Opening with the wrong mode silently destroys data when you meant to read. Forgetting to check null crashes on the first use of the stream. Mixing text and binary modes on the same file leads to confusing results, especially on systems that translate newlines in text mode.

Another frequent issue is leaving a file open inside a loop while opening it again each pass. Either open once outside the loop or close carefully before the next open.

Key Takeaways

💡

  • fopen opens a stream and returns null on failure
  • Modes control read, write, append, and text versus binary behavior
  • Text functions format human-readable data, binary functions move raw records
  • Check open and read or write results before trusting data
  • Close every file you open so buffers flush and resources free

Practice Questions

  1. What is the difference between w mode and a mode when opening a file?
  2. Why should you check the return value of fopen before using the pointer?
  3. When is binary file I/O more appropriate than text file I/O?

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert C Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement