Foundations · Module 4
Structs, Enumerations and Files
Group related values into structs and enumerations, read and write files with streams, and combine everything from Foundations in a small multi-file program.
Programs need to represent things, such as a contact, a state or a record, and to keep them after the program ends. This module covers structs and enumerations, which give shape to data in memory, and file streams, which carry it to and from the disk. It closes with a small contact book that uses everything from the Foundations level.
- 1Structs: Grouping Related DataCombine values of different types into one type with struct, see members laid out at fixed offsets in memory, and learn what copying and initializing structs do.8 min
- 2Struct Layout, Padding and AlignmentSee why a struct is often larger than the sum of its members, how alignment rules place each member and pad the end, and how reordering members and checking layouts saves memory and avoids file-format traps.8 min
- 3Passing, Returning and Pointing to StructsCompare passing a struct by value, by reference and by pointer, learn what the arrow operator does, and see why returning a struct by value is usually free thanks to copy elision.8 min
- 4Enumerations: enum and enum className a small set of values with an enumeration, see that it is an integer underneath, and learn why enum class avoids name clashes and accidental conversions and how switch warnings keep your code up to date.7 min
- 5Writing Text Files With ofstreamWrite data to a file with std::ofstream, see how the stream buffers text before the operating system writes it, and learn to open files safely, choose truncate or append, and write records that can be read back.8 min
- 6Reading Text Files and Handling Errors With ifstreamRead a file line by line with std::ifstream, tell a normal end of file from a real error using the stream state, and handle empty files, missing newlines, Windows line endings and malformed lines.8 min
- 7Binary Files: Writing and Reading Raw BytesStore values as raw bytes with write and read, see why size, byte order and padding make naive dumps non-portable, and design a small binary format with fixed-width types, a header and fixed-size records.8 min
- 8Parsing Lines: Splitting Text and Converting FieldsRead a line, split it into fields, convert text to numbers, and handle malformed input without crashing.10 min
- 9Project: A Contact Book Across Several FilesBuild a multi-file contact book: structs, file I/O, line parsing, and a simple build script that compiles everything into one program.12 min