Quiz 2

File I/O — fopen, fread, fwrite, fprintf, Binary vs Text

555 words
3 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# File I/O — fopen, fread, fwrite, fprintf, Binary vs Text ## 🎯 Learning Objectives - Open, read, write, and close files - Use formatted I/O (fprintf, fscanf) - Read/write binary data structures - Handle file I/O errors properly * * * ## 1. File Operations ### 1.1 Opening and Closing Files ### 1.2 File Modes Mode M...

File I/O — fopen, fread, fwrite, fprintf, Binary vs Text

🎯 Learning Objectives

  • Open, read, write, and close files
  • Use formatted I/O (fprintf, fscanf)
  • Read/write binary data structures
  • Handle file I/O errors properly

1. File Operations

1.1 Opening and Closing Files

c
FILE *fp = fopen("data.txt", "r");  // Open for reading
if (fp == NULL) {
    perror("Failed to open file");
    return -1;
}
// Process file...
fclose(fp);  // Always close!

1.2 File Modes

ModeMeaningFile ExistsFile Doesn't Exist
"r"Read textOpenError (returns NULL)
"w"Write textOverwriteCreate new
"a"Append textAppend to endCreate new
"r+"Read/WriteOpen (no truncate)Error
"w+"Read/WriteOverwriteCreate new
"a+"Read/AppendRead + AppendCreate new
"rb"Read binarySame as "r"Same as "r"
"wb"Write binarySame as "w"Same as "w"

2. Text I/O

2.1 fprintf and fscanf

c
// Writing
FILE *out = fopen("output.txt", "w");
fprintf(out, "Name: %s, Age: %d, GPA: %.2f\n", "Alice", 22, 3.75);
fclose(out);
// Reading
FILE *in = fopen("output.txt", "r");
char name[50];
int age;
float gpa;
fscanf(in, "Name: %s, Age: %d, GPA: %f", name, &age, &gpa);
fclose(in);

2.2 fgets and fputs

c
char buffer[256];
// Read a line
if (fgets(buffer, sizeof(buffer), fp) != NULL) {
    printf("Read: %s", buffer);
}
// Write a string
fputs("Hello, World!\n", fp);

3. Binary I/O

3.1 fread and fwrite

c
typedef struct {
    int id;
    char name[50];
    double salary;
} Employee;
// Write binary
Employee emp = {1, "Alice", 75000.0};
fwrite(&emp, sizeof(Employee), 1, fp);
// Read binary
Employee emp_read;
fread(&emp_read, sizeof(Employee), 1, fp_type");

3.2 Binary vs Text

AspectTextBinary
ReadabilityHuman-readableMachine-only
SizeLarger (digits)Compact
PortabilityNewline issuesPlatform-specific
PrecisionRounding in floatsExact representation

4. 📝 Practice Questions

Q1: What happens if you fopen a non-existent file with mode "r"?
Answer: fopen returns NULL. Always check the return value before using the FILE pointer. errno is set to ENOENT (or similar) and perror can report the error. Q2: Write a program that copies one file to another.
c
void copy_file(const char *src, const char *dst) {
    FILE *in = fopen(src, "rb");
    FILE *out = fopen(dst, "wb");

    if (!in || !out) { perror("Error"); return; }

    char buffer[4096];
    size_t bytes;
    while ((bytes = fread(buffer, 1, sizeof(buffer), in)) > 0) {
        fwrite(buffer, 1, bytes, out);
    }

    fclose(in);
    fclose(out);
}
Q3: Why should you always close a file after using it?
Answer: To flush any buffered data to disk, release system resources (file descriptors are limited), and prevent data loss. The OS will close files when the program exits, but it's poor practice to rely on this. Q4: What is the difference between fgets and gets?
Answer: fgets takes a size parameter (maximum characters to read), preventing buffer overflow. gets has NO size check and will overflow any buffer. gets was removed from the C11 standard. Q5: When would you use binary mode instead of text mode?
Answer: When reading/writing structured data (C structs, arrays of numbers), binary data (images, executables), or when exact byte representation matters. Binary avoids conversion overhead and precision loss.

5. 🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.