CSSE 132 Mini-reading · I/O

Linux I/O: Files, Streams, and Buffers

Follow bytes from a file into a C array, then back out again. Review stream handles, byte counts, strings, and file positions in about 8–10 minutes.

Why This Matters

Your C program keeps working data in memory, but it needs I/O to read a document, accept keyboard input, or save results. Worksheet 18 connects these operations to arrays, pointers, and command-line arguments. The important questions are: which stream are you using, how many bytes actually moved, and where will the next read begin?

Core Idea

Linux models many I/O resources as files: regular disk files, terminals, and device interfaces can be accessed through a common set of operations. “Everything is a file” is a useful organizing idea. It does not mean every resource is an ordinary disk file or supports every operation; for example, you cannot seek backward through keyboard input.

Standard streams

stdin is standard input, normally connected to the keyboard. stdout is standard output, normally connected to the terminal. stderr carries diagnostic messages. These connections can be redirected by the shell.

A handle is not the data

A FILE * identifies a C library stream. A character array holds the bytes you read. Opening a stream does not read the entire file into your array.

The slides introduce two related interfaces. POSIX I/O uses integer file descriptors with open, read, write, and close. C stream I/O uses FILE * with fopen, fread, fwrite, and fclose. Standard descriptors are 0 for input, 1 for output, and 2 for diagnostics. Keep each handle with its matching function family.

C streams buffer data in memory to reduce underlying I/O calls. “Unbuffered” POSIX I/O bypasses this C stream buffering; it can still request many bytes per call, and the operating system can still cache data. The examples below use C streams to match Worksheet 18.

Worked Examples

1. Read a short message safely

This complete program reads up to seven bytes from a named text file and displays them. It deliberately performs one read so you can trace the count before considering a loop.

A stream, a buffer, and an actual count
C codeWhat this does
#include <stdio.h>

int main(int argc, char **argv) {

Start a standard C program. stdio.h declares the stream functions.

    if (argc != 2) {
        fprintf(stderr, "Usage: %s file\n", argv[0]);
        return 1;
    }

Check that a filename exists before using argv[1]. Send usage information to the diagnostic stream.

    FILE *input = fopen(argv[1], "r");
    if (input == NULL) {
        perror("fopen");
        return 1;
    }

Open for reading. A failed open returns NULL; do not read through that handle.

    char buffer[8];
    size_t count = fread(buffer, 1, 7, input);
    buffer[count] = '\0'; // terminate this chunk

Request seven one-byte items and reserve the eighth slot for a string terminator. fread returns the number of complete items read.

    printf("%s", buffer);
    int failed = ferror(input);
    if (fclose(input) != 0) failed = 1;
    return failed ? 1 : 0;
}

Print the terminated text, check for a read error, and close the stream. Return a failure status if reading or closing failed.

Run it as ./read-message message.txt. If the file contains exactly HELLO, fread returns 5. The valid data occupies indices 0 through 4; index 5 receives the terminator. Printing with %s stops there. Setting only buffer[7] would leave unread positions between the data and terminator, potentially printing old or uninitialized bytes.

Items versus bytes

fread(buffer, size, count, input) returns an item count. With size 1, items and bytes match. A request for seven bytes may return fewer at end of file. fread does not append a null character; that is your responsibility when treating the bytes as a C string.

2. Repeat until there is no more data

After successfully opening input, replace the single read with this text-processing loop. Keep the error check and close from the complete program.

char buffer[8];
size_t count;
while ((count = fread(buffer, 1, 7, input)) > 0) {
    buffer[count] = '\0'; // terminate each new chunk
    printf("%s", buffer);
}

For a ten-byte text file, successive counts are 7, 3, and 0. Each read advances the file position by the bytes it consumed. The second read starts where the first ended. A zero count ends this loop; use ferror(input) afterward to distinguish an error from normal completion.

This string-based approach assumes text without embedded null bytes. To output raw bytes, use fwrite(buffer, 1, count, output) and check that its return value equals count. It needs no terminator and does not stop at an embedded null. fprintf(output, "%s", buffer) instead interprets buffer as a string, just as printf does.

3. Move the file position

Imagine a regular Linux file containing exactly ABCDEFGHIJKL: twelve bytes, with no final newline. With an already opened, seekable input stream:

if (fseek(input, 0, SEEK_END) != 0) { /* handle error */ }
long length = ftell(input); // 12; check for -1L on error
if (fseek(input, 4, SEEK_SET) != 0) { /* handle error */ }

The first operation moves to the end. ftell reports the position, 12 bytes from the beginning. The last operation moves to offset 4, so the next read begins at E. Offsets start at zero: A is at 0, B at 1, and E at 4. These are illustrative statements, not a complete error-handling program.

Worksheet 18 asks you to apply this reasoning to a different starting position. Plan the position first, then read and write chunks. Seeking moves the position; it does not itself copy data. For these ordinary Linux files, positions count bytes, not lines or necessarily displayed characters.

Use "r" to open an existing file for reading and "w" to create a file for writing or truncate an existing one. Check both opens before proceeding. Choose a distinct output filename: opening the source itself with "w" destroys its old contents.

Common Mistakes

Using the requested count

A request for seven bytes does not guarantee seven were read. Process the returned count, especially for the last chunk.

Confusing bytes and strings

fread supplies bytes. A %s conversion needs a null-terminated string. Leave room for the terminator and put it immediately after the actual data.

Confusing status and position

fseek returns zero on success, not the new position. Use ftell for the position; store it in a long.

Mixing interfaces

Pass a FILE * to fclose and an integer descriptor to close. POSIX read/write return ssize_t, which can represent -1 for an error.

Quick Reference

TaskC stream operation
Open / closefopen(path, "r") / fclose(stream)
Read bytesfread(buffer, 1, capacity, stream); returns actual byte count when size is 1
Read text line or part of onefgets(buffer, capacity, stream); stores at most capacity − 1 characters and appends a null on success; retains a newline if read
Write formatted textfprintf(stream, "%s", buffer)
Write raw bytesfwrite(buffer, 1, count, stream); check returned count
Choose positionfseek(stream, offset, SEEK_SET); SEEK_CUR uses current position, SEEK_END uses end
Report positionftell(stream); long result, −1L on failure

Check Yourself

Try these before opening the answers.

  1. How do a FILE * and a char array play different roles during a read?
  2. A nine-byte text file is read in chunks of four one-byte items. What counts do successive fread calls return, assuming no errors?
  3. You read three bytes into char buffer[8]. Where should you put the null terminator before using %s?
  4. In the twelve-byte example, what character comes next after a successful fseek(input, -3, SEEK_END)?
  5. What is wrong with storing fseek's return value as the file length?

Answers

Show the answers
  1. The FILE * identifies the stream; the array stores the bytes copied into memory.
  2. 4, 4, 1, then 0. Only nine bytes exist; the requested size is an upper bound.
  3. At buffer[3]. Indices 0–2 hold the three bytes, and index 3 must end the string.
  4. J. The end is offset 12; three bytes back is offset 9.
  5. fseek reports success or failure. Seek to the end, check success, then call ftell to obtain the position.

Next Step

Complete Worksheet 18: Input/Output I. For each read, mark the stream, requested capacity, actual count, and next file position before filling in code.