YOUR C LEARNING COMPANION

Find your next idea.

Learning path
Working with inputChapter 56 of 73

Ownership, cleanup, and partial work

Follow a checked file copy through acquisition, short transfers, close failures, borrowing, and partial-output limits.

6 min readIntermediateC17 baseline
Offline reading
In this chapter8 sections

A task can acquire several resources and fail halfway through. Cleanup means tracking which resources were acquired and releasing them on the right paths. We will also distinguish releasing a resource from undoing work already written outside the program.

1. Record what the function owns

A cleanup path releases resources whose acquisition succeeded. Ownership says who performs that release; borrowing says who can temporarily use the resource without taking responsibility for its lifetime. Initialize owned pointers to NULL, acquire in a clear order, and release each acquired resource once. Do not close stdin/stdout merely because a helper happened to receive those pointers.

Two acquisitions, three ownership states
Nothing opened
Nothing to close
Input opened
Close input if output acquisition fails
Both opened
Close output and input on every later exit
Cleanup order is chosen deliberately; a close failure does not cancel cleanup of the other stream.

2. Follow one checked copy through its failure paths

This C17 program copies from an existing binary input to a newly created binary output. The wbx mode refuses an already existing destination, including the source path itself. The two command-line arguments are source and destination names. The core helper owns both streams; the caller owns only the choice of names and how to report status.

Complete C17 program
#include <stdio.h>
#include <stdlib.h>

static int copy_file(const char *source_name, const char *target_name)
{
    FILE *input = NULL;
    FILE *output = NULL;
    int status = EXIT_FAILURE;
    input = fopen(source_name, "rb");
    if (input == NULL) goto cleanup;
    output = fopen(target_name, "wbx");
    if (output == NULL) goto cleanup;

    unsigned char block[256];
    size_t count;
    while ((count = fread(block, 1, sizeof block, input)) != 0) {
        if (fwrite(block, 1, count, output) != count) goto cleanup;
    }
    if (ferror(input)) goto cleanup;
    status = EXIT_SUCCESS;

cleanup:
    if (output != NULL && fclose(output) == EOF) status = EXIT_FAILURE;
    if (input != NULL && fclose(input) == EOF) status = EXIT_FAILURE;
    return status;
}

int main(int argc, char *argv[])
{
    if (argc != 3) return EXIT_FAILURE;
    if (copy_file(argv[1], argv[2]) != EXIT_SUCCESS) {
        fputs("Copy failed; output may be incomplete.\n", stderr);
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

goto jumps to a label in the same function. Here it gathers failure exits at one cleanup section and avoids duplicating releases after each operation. It does not jump into a variably modified scope. The first failure keeps status as EXIT_FAILURE; only a completed read/write loop promotes it to success. A short write or a read error leaves failure selected, and each fclose can turn a provisional success back into failure.

3. Closing is an operation, not merely tidying up

A successful buffered fwrite can be followed by failure during fclose. Checking only writes would miss that final failure. Each handle is used for one close attempt and then abandoned; even an EOF result does not permit another fclose on it. Cleanup continues for the remaining owned stream. A non-null pointer does not by itself prove that its target is still open after a close.

The function reports a combined failure status. A larger application may separately preserve the first operation failure and any cleanup failure for diagnostics. Capture valid diagnostic details before cleanup can replace them. Do not invent errno details when the operation does not guarantee them. Returning from main or calling exit performs normal stream cleanup, but explicit close is needed when the program must observe and report close failures.

4. Releasing resources does not undo partial work

If copying fails after creating the output, a partial file may remain. Closing it is still required, but cleanup does not promise an all-or-nothing file transaction. A production replacement workflow may use a temporary file, validated flush/close, and a documented replacement operation; cross-platform atomic replacement and physical durability need additional platform guarantees. This teaching example never claims those properties.

5. A borrowed stream keeps its owner

Complete C17 program
#include <stdio.h>
#include <stdlib.h>

/* Borrow stream for this call; do not close it. */
static int write_heading(FILE *stream)
{
    return fputs("CodedileRead\n", stream) == EOF ? -1 : 0;
}

int main(void)
{
    if (write_heading(stdout) != 0) return EXIT_FAILURE;
    return fflush(stdout) == EOF ? EXIT_FAILURE : EXIT_SUCCESS;
}

The helper writes a heading but does not close the stream or claim that buffered output has reached its final destination. Its caller decides when to flush or close. This separation makes the helper reusable with stdout, a file, or another suitable output stream. Document lifetime and access preconditions even when the interface contains only a FILE pointer.

Primary references and further reading

Before you move on

  • Cleanup depends on which resources were successfully acquired before a failure.
  • Ownership determines who must release each resource and when references become invalid.
  • Closing resources does not automatically undo external partial work or prove durable storage.
Keep these ideas separate
Cleanup / Rollback
Cleanup releases owned resources; rollback is an additional policy for undoing committed or partial effects.
Explain it in your own words

Which resources and partial effects would you track if copying a file fails halfway through?

Optional: say it aloud or keep a note. You can continue whenever you are ready.

Check your understanding

Optional. Answers are not saved or sent, and reading stays unrestricted.

A function acquires one resource, then acquiring a second fails. What should its failure path account for?
Read the explanation for every choice
  1. Release every imagined resource, even those never acquired.

    Cleanup must follow actual acquisition state and the resource’s API contract.

  2. Return immediately and leave the first resource owned by nobody.

    Losing ownership can leak the first resource.

  3. Release or transfer the first resource according to the ownership contract.

    ✓ Correct reasoning. Partial work still creates cleanup obligations for resources already acquired.

C17

Ready for the next idea?

Mark this chapter as read whenever you feel ready.

CHAPTER 56 / 73

In this chapter

Ownership, cleanup, and partial work

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping