Block I/O, positions, and update streams
Count complete transfer elements, handle partial records, follow update-stream transitions, and interpret file positions carefully.
In this chapter8 sections
Block I/O transfers elements between storage and a stream. A short transfer needs interpretation, and a saved file position is not always a simple byte number. We will separate transfer counts, position rules, and external data formats.
1. fread and fwrite count complete elements
fread(pointer, size, count, stream) requests count elements of size C bytes. Its return counts complete elements, not necessarily bytes. Setting size to one makes the return a byte count and simplifies chunk processing. fwrite has the analogous count contract. These functions can operate on text or binary streams; choosing them does not secretly switch a stream’s mode.
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
const unsigned char source[] = { 0x43, 0x00, 0xff };
unsigned char copy[sizeof source];
FILE *stream = tmpfile();
if (stream == NULL) return EXIT_FAILURE;
int status = EXIT_FAILURE;
if (fwrite(source, 1, sizeof source, stream) != sizeof source) goto cleanup;
if (fseek(stream, 0, SEEK_SET) != 0) goto cleanup;
if (fread(copy, 1, sizeof copy, stream) != sizeof copy) goto cleanup;
assert(memcmp(source, copy, sizeof source) == 0);
status = EXIT_SUCCESS;
cleanup:
if (fclose(stream) == EOF) status = EXIT_FAILURE;
return status;
}
The array contains three bytes including an embedded zero. The count, rather than a null terminator, defines the payload. tmpfile creates a temporary binary update stream, so the successful seek both returns to the start and provides the output-to-input transition. Every operation is checked before the next stage uses its result. The goto cleanup label ensures the owned stream is closed on all later paths.
2. A short transfer needs interpretation
A short transfer returns fewer complete elements than requested. For input, inspect feof and ferror after the short result; for output, treat an incomplete required write as failure. Do not process unfilled elements or assume a missing suffix is automatically zero. If an element is only partly read, its value is indeterminate; the count has not promoted it to a complete record.
Inspect a partial-element example
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const unsigned char source[] = { 10, 20, 30 };
unsigned char items[2][2];
FILE *stream = tmpfile();
if (stream == NULL) return EXIT_FAILURE;
int status = EXIT_FAILURE;
if (fwrite(source, 1, sizeof source, stream) != sizeof source) goto cleanup;
if (fseek(stream, 0, SEEK_SET) != 0) goto cleanup;
size_t complete = fread(items, sizeof items[0], 2, stream);
if (ferror(stream)) goto cleanup;
assert(complete == 1);
assert(items[0][0] == 10 && items[0][1] == 20);
/* Do not interpret the incomplete second item as a complete value. */
status = EXIT_SUCCESS;
cleanup:
if (fclose(stream) == EOF) status = EXIT_FAILURE;
return status;
}
On the checked host, the three-byte temporary payload supplies one complete two-byte item and part of the next. Only the first is interpreted. Standard binary-stream rules permit an implementation-defined number of null characters appended to a file, so exact physical end behavior is not a universal file-size promise. Define external formats and accepted trailing data rather than inferring them from this one host’s result.
3. Update streams require direction transitions
| Transition | Required intervening operation |
|---|---|
| Output → input | fflush or a file-positioning operation |
| Input → output | A file-positioning operation, unless that input operation encountered end-of-file |
These are sequencing requirements, not merely visual cursor movement. An output flush does not move back to the start, and a newline does not replace the transition. For input-to-output, fflush alone is not the required positioning operation. Successful fseek/fsetpos clear the EOF indicator; they do not generally clear the stream’s error indicator. Rewind also clears the error indicator but has no return value for checking position failure.
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *stream = tmpfile();
if (stream == NULL) return EXIT_FAILURE;
int status = EXIT_FAILURE;
if (fputc('A', stream) == EOF) goto cleanup;
if (fseek(stream, 0, SEEK_SET) != 0) goto cleanup;
int first = fgetc(stream);
if (first != 'A') goto cleanup;
if (fseek(stream, 0, SEEK_CUR) != 0) goto cleanup;
if (fputc('B', stream) == EOF) goto cleanup;
if (fseek(stream, 0, SEEK_SET) != 0) goto cleanup;
int again = fgetc(stream);
int second = fgetc(stream);
assert(again == 'A' && second == 'B');
status = EXIT_SUCCESS;
cleanup:
if (fclose(stream) == EOF) status = EXIT_FAILURE;
return status;
}
4. A position token is not always a byte index
For a text stream, a portable fseek uses offset zero, or a value returned by a successful earlier ftell for that same file with SEEK_SET. Such an ftell value is not necessarily a byte count; arithmetic on it is not a portable text-file navigation method. For binary streams, positions count characters from the beginning, but meaningful SEEK_END support is not required. Check fseek for nonzero failure and ftell for -1L.
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *stream = tmpfile();
if (stream == NULL) return EXIT_FAILURE;
int status = EXIT_FAILURE;
if (fputs("AB", stream) == EOF) goto cleanup;
if (fseek(stream, 0, SEEK_SET) != 0) goto cleanup;
int first = fgetc(stream);
if (first != 'A') goto cleanup;
fpos_t mark;
if (fgetpos(stream, &mark) != 0) goto cleanup;
int second = fgetc(stream);
if (second != 'B') goto cleanup;
if (fsetpos(stream, &mark) != 0) goto cleanup;
int repeated = fgetc(stream);
assert(repeated == 'B');
status = EXIT_SUCCESS;
cleanup:
if (fclose(stream) == EOF) status = EXIT_FAILURE;
return status;
}
fpos_t is an abstract position type; do not assume it is an integer offset. fgetpos/fsetpos save and restore the stream position and associated multibyte conversion state where applicable. They do not restore application variables, reverse earlier file writes, or recreate a parser’s own state. A bookmark from one file is not permission to position an unrelated stream.
5. Transfer bytes; design the format separately
Writing sizeof record bytes from a structure may expose padding and implementation-specific integer or pointer representations. Binary mode does not make that representation portable. Design field sizes, ranges, byte order, versioning, and validation explicitly. Also validate any size-times-count arithmetic and the actual live buffer region before a transfer. A successful block call is neither schema validation nor proof of durable storage.
Primary references and further reading
- WG14 N1570 — public C11 committee draft: 7.21.2–7.21.3, 7.21.5.3, 7.21.8–7.21.10. Stable core provisions used for the C17 baseline; not the final ISO publication.
For a complete bounded encoding example, see External data formats. It defines fields independently of a structure’s memory layout.
Before you move on
- Block I/O reports complete transferred elements rather than a promise that the entire request succeeded.
- Position tokens and text-stream offsets follow specific stream rules.
- Update streams require the correct transitions between reading and writing.
Keep these ideas separate
- File position / Universal byte index
- A saved stream position can carry implementation state and is not always a simple external byte number.
What would you inspect after a short block read before deciding whether it is a final record or an error?
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.
Read the explanation for every choice
- The number of elements successfully written.
✓ Correct reasoning. The result counts elements. With an element size of one byte, it also directly gives the byte count.
- Always the total requested number of bytes.
The result reports completed elements and can be short.
- A guarantee that no later flush or close can fail.
Buffered output can encounter errors later; success here is not that broader guarantee.
C17
Ready for the next idea?
Mark this chapter as read whenever you feel ready.