Chapter 14: Processing and I/O
Level 2 — Cognition
Text processing, formatted I/O, character encodings -- how C handles data flowing in and out, and how Auto simplifies it.
Input and output are where programs meet the outside world. C's I/O library, centered on stdio.h, provides a flexible but error-prone set of tools. This chapter covers text processing, formatted input, character encodings, and binary streams -- and how Auto provides safer alternatives.
14.1 Text Processing
C provides character classification functions in <ctype.h>:
// C Deep Dive: character classification
#include <ctype.h>
int ch = 'A';
isalpha(ch); // true: alphabetic
isdigit(ch); // false: not a digit
isupper(ch); // true: uppercase
islower(ch); // false: not lowercase
isspace(ch); // false: not whitespace
toupper(ch); // 'A' -> 'A'
tolower(ch); // 'A' -> 'a'These functions have a critical caveat: passing a value not representable as unsigned char or EOF is undefined behavior. In practice, this means passing a char from a platform where char is signed can cause UB for characters with values above 127.
String operations in <string.h>:
// C Deep Dive: string operations
strlen("hello"); // 5
strcpy(dst, src); // copy -- dst must be large enough!
strcat(dst, src); // concatenate -- dst must be large enough!
strcmp("abc", "def"); // negative: abc < def
strncmp("abc", "abd", 2); // 0: first 2 chars equal
strchr("hello", 'l'); // pointer to first 'l'
strstr("hello", "ell"); // pointer to "ell"The strcpy and strcat functions are responsible for many buffer overflow vulnerabilities. C11 added strncpy_s and strcat_s as safer alternatives, but they remain underused.
Auto's approach: safe string operations. Auto strings are length-tracked and immutable. Operations that could overflow simply do not arise:
// Auto: safe text processing
fn count_words(text str) int {
var count int = 0
var in_word bool = false
for i in 0..len(text) {
let ch str = str(text[i])
if ch == " " {
in_word = false
} else {
if !in_word {
count = count + 1
}
in_word = true
}
}
count
}