Decoded: fold (coreutils)

[Back to Project Main Page]

Note: This page explores the design of command-line utilities. It is not a user guide.
[GNU Manual] [POSIX requirement] [Linux man] [FreeBSD man]

Logical flow of fold command (coreutils)

Summary

fold - wrap input lines to fit in specified width

[Source] [Code Walkthrough]

Lines of code: 310
Principal syscall: fwrite()
Support syscall: fadvise()
Options: 8 (3 short, 5 long)

Descended from fold introduced in 4.3BSD (1986)
Added to Textutils in November 1992 [First version]
Number of revisions: 126 [Code Evolution]

fold is the weaker, but more straight-forward form of the fmt utility

Helpers:
  • adjust_column() - Calculates column effect based on input character
  • fold_file() - Performs the fold operation on a single target file
External non-standard helpers:
  • die() - Exit with mandatory non-zero error and message to stderr
  • error() - Outputs error message to standard error with possible process termination

Setup

fold defines a few globals including:

  • The break_spaces flag indicates if lines should be broken only on spaces
  • The count_bytes flag indicates counting by bytes
  • The have_read_stdin flag is set if STDIN was read at least once

main() defines a few variables before parsing:

  • i - Generic iterator for files to fold
  • optc - The character for the next option
  • ok - The exit status of the problem
  • width - The width of lines to fold to

Parsing

Parsing for fold digs in to a few basic formatting questions:

  • How wide are the lines?
  • Do we count by column or by bytes?
  • Should we line break only on spaces?

Parsing failures

There are a few parsing failures checked:

  • Invalid column count
  • Unknown options are used

Execution

fold execution is fairly straight-forward:

  • For each input file (or STDIN), open an input stream
  • Read in a single character
  • Count the character and handle newline counts
  • If the column has exceeded the given width...
    • If we must break on a space, scan backwards for the first space
    • Otherwise, break here and write the current line as processed
  • Repeat character reads until EOF
  • Write the last line processed
  • Check for any errors during folding

Failure cases:

  • Unable to open input file stream
  • Errors on write

All failures at this stage output an error message to STDERR and return without displaying usage help


[Back to Project Main Page]