Designing a File-Driven Record System | C++ Programming

UPI Study › Courses › C++ Programming › Free lessons › Lesson 10.3 Free with a free account

Designing a File-Driven Record System

C++ Programming · Chapter 10: File Access and MemorySection 10.3 · lesson 71 of 84video coming soon

← Decimal and Text in File StreamsNext lesson: Applied Challenge: File Operation Exercises →

Earn 3 college credits for C++ ProgrammingRecommended for credit by NCCRS · Computer Science 242 · self-paced · one payment, lifetime access

In this lesson

An applied challenge.

  • Design and document a fixed-layout record
  • Compute any record's position, and read or write it
  • Delete without moving any other record
  • Build the system in stages you can prove

Transcript

Everything said in the video, section by section (1,646 words). Read along, or search it.

Opening

Combining Tools Into One Inventory System

Everything needed for a small working system is now in hand. Records grouped into one unit, files that survive the program ending, and the ability to jump straight to a position. This section puts them together into one program: an inventory that can be added to, searched, corrected, and reported on. And the hardest part of it is a decision made before any code is written.

File Picture

One File of Numbered Slots

The program keeps one data file. Every item occupies exactly one slot, and slots are numbered from zero. Each line holds a status, a code, a name, a quantity, and a price. A for active. D marks a free slot, like the eraser in slot two.

Core Rule

Every Operation Is Slot Plus Access

Every operation is some combination of work out which slot, and read or write that slot. The position of slot n in the file is the slot times the record size. The menu is a thin layer on top, and it changes rarely. Almost all of the thinking is underneath it. And the layout decision is permanent, because every file already written obeys it.

Design Decision

Why Records Need Fixed Length

Jumping to a record means knowing where it starts, and the only way to know that without reading everything before it is arithmetic. If every record is fifty-four characters, record two begins at two times fifty-four, one hundred eight. One multiplication, and no reading. Let records vary in length, and record two's position is unknown until records zero and one have been read. Jumping becomes impossible. Only scanning works.

Trade-Off

Wasted Space for Readable Fixed-Width Text

The price of the fixed scheme is wasted space in short fields, and a hard limit on long ones. That's a trade you're making deliberately. This system stores records as fixed-width text: every field padded with spaces, and every record ending in a newline. So you can open the file in any editor, and see immediately whether you wrote what you meant.

Layout Table

Writing the File Format Down First

Before any code, write the layout down. This table is the file format. Status, one character at position zero: A for active, D for deleted, and never anything else. Code, six characters from position one: unique among active records. Name, thirty characters from position seven, with longer names cut to fit. Quantity, six characters from thirty-seven: never negative. Price, ten characters from forty-three, in rupees with two decimal places. And the newline at fifty-three, included in the size so slots line up with lines. The total is fifty-four. This table is what lets a second program read your data, and lets you read it in six months. Every width is a commitment, because files already written can't be re-measured.

Quick Check

Finding the Start of Slot Five

Quick check. With fifty-four-character records, where does slot five start? Pause and work it out. At byte two hundred seventy. Slot times record size. No reading, no scanning.

Code Constants

Named Widths and the Fit Function

In code, the widths become named constants, and the record size is fifty-four: fifty-three characters of fields, plus the newline. One small function does a lot of work. Fit to resizes a string to exactly the given width. If the text is short, it's padded with spaces. If it's long, it's cut. Either way, the result is exactly that width. So a forty-character name gets cut, rather than pushing every later field out of position. Run it: pen is padded out to ten, a long name is cut to thirty, and the widths plus the newline come to fifty-four.

Deletion Design

Marking Records Deleted Instead of Removing

Removing a record physically, closing up the gap, would shift every record after it to a new position. Every slot number anybody had recorded would then be wrong, and the benefit of computing positions would be lost on every deletion. So records aren't removed. The status character is overwritten with D, and the slot keeps its position. Searches skip it, and the report ignores it. Deleting the eraser writes one character. Adding a marker pen looks for the first slot marked D, and reuses it. Only when there's no free slot does the file grow by one. And records zero, one and three never move, so nothing that referred to them breaks.

Operations

Each Action as Position and File Step

Each operation is a position question, followed by a file action. Add scans for the first slot marked D. If there's none, the position is the current number of slots. It rejects a code an active record already holds, then writes a complete record. Search scans from slot zero, comparing codes and skipping deleted slots, and reports the record, or that it isn't stocked. Modify uses the same scan. It reads the record, changes the fields, seeks back to the same position, and writes the whole record again. Delete uses the same scan, and writes a single D over the status. And report needs no searching: it reads every slot in turn, skips the deleted ones, and prints the rest with a total.

Core Functions

Read and Write Record Arithmetic

Two operations contain the arithmetic everything else depends on. Write record seeks the put marker to slot times record size. Then it writes the status, and each field fitted to its width, then a newline, and flushes. Read record seeks the get marker to the same position, reads the line, and cuts each field out by its start and width, converting the numbers. One detail a sketch leaves out. A field read back still carries its padding, so the code holds P one zero zero one, with a trailing space. Trim that padding as each field is read. Otherwise every search fails to match a code typed without it, and the failure looks like a missing record, rather than a comparison problem.

Common Mistake

Deriving Offsets From Width Constants

Every width in that code appears twice. The positions one, seven, thirty-seven and forty-three come from adding up the widths above each field. Typed as bare numbers, they go out of date silently: change the name width, and two of those numbers become wrong. The program still builds, and every record reads back scrambled. So derive the offsets from the width constants, as these lines do. Either way, the layout table is the single source of truth that both halves must agree with. Change the name width to thirty-five here, and the static assert refuses to build until the record size is updated too.

Build Strategy

Proving the Program One Stage at a Time

Written all at once, this program produces a first run in which nothing works, with six candidate reasons. Built in stages, each can be proven before the next. Stage one: the layout and the width constants, with no file operations. Move on when the widths add up to the record size. Stage two: write record only. Write two records, and open the file in an editor. You should see two lines of exactly the same length, with fields where the layout says. Stage three: read one back, and check it matches. Stage four: the scan, finding present codes and reporting absent ones. Stage five: add with reuse, modify, and delete. Stage six: the menu and the report. And keep a file you can throw away. Every fault in this kind of program damages data. With a pristine copy beside it, restoring takes two seconds.

Demo Run

The Finished Sequence in Action

Here is the finished sequence running. Four items go in. A duplicate code is refused, so the answer is zero. The eraser is deleted, then the marker pen is added, and it lands in slot two, the freed one. The notebook's quantity changes to a hundred. A search finds P one zero zero five in slot two, and a missing code gives minus one. The report skips nothing active, and the file on disk shows four lines of fifty-three characters, exactly where the layout says they are.

Exercise

Layout Document, Program, and Evidence

Now the exercise. Three things are submitted, and the first isn't the program. A layout document: one page with the field table, the record size, the meaning of every status value, and each field's rules. It's checked for whether someone who's never seen your program could read your file with it alone. The program: add, search, modify, delete, report and quit, behind a menu, with deleted slots reused, and the file opened once and kept open. And evidence it works: the data file before and after, and the output of each option, including the awkward cases.

Marking Cases

Edge Cases the Marking Checks

Here are the cases the marking will look for. An empty file: report prints a heading and no rows, and search reports nothing found. A code that isn't there: search, modify and delete must say so, rather than acting on slot zero by default. A duplicate code must be refused. Over-length input: a forty-character name must be cut to fit. Delete then add: the new item lands in the freed slot, and everything after it stays put. And an unrecognized menu choice: the program says so, and shows the menu again.

Key Terms

Slots, Logical Deletion, and Reuse

A few key terms. A fixed-layout record gives every field an agreed width, so every record occupies the same number of characters. A slot is a numbered position, one record long. Slot n begins at n times the record size. Logical deletion marks a record unused rather than removing it, so later records keep their positions. Slot reuse writes a new record into a slot marked deleted. And the layout document is the written description of the format, which the file depends on, and can't contain.

Think About It

What an Uncut Name Does

Here's something to think about. A forty-character name is written into a thirty-wide field, without being cut. What happens to the file? Pause and think. Every field after it shifts along by ten. That record is longer than the others, so the lines are no longer equal. From then on, every computed position lands in the wrong place. The slot after it starts in the middle of the long name, and reads garbage.

Key Takeaways

Fix Widths, Mark Deletions, Build in Stages

To summarize. Fix every field's width, and write the layout down before any code. Slot n starts at n times the record size. Pad or cut every field to exactly its width when writing, and trim it when reading. Delete by marking, and add by reusing. And build and prove one stage at a time.

About C++ Programming at UPI Study

C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Why take it here

Why students take C++ Programming with UPI Study

Your first real programming languageC++ teaches how programs really work: variables, control flow, functions, memory and objects. It is the base for data structures, algorithms, systems and game programming, and for most computer-science degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

C++ Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Designing a File-Driven Record System

How do you find where a record starts in a fixed-length record file in C++?
Multiply the record's slot number by the record size, then seek to that byte. With 54-character records, slot 5 starts at byte 270 and slot 2 at byte 108. No earlier records are read. For example, in.seekg(slot * RECORD_SIZE) positions the get marker, and seekp does the same for writing.
Why do records in a file need to be the same length if you want random access?
Equal lengths let you compute any record's start with one multiplication instead of reading everything before it. If record lengths vary, record 2's position stays unknown until records 0 and 1 have been read, so only scanning works. The trade-off is wasted space in short fields and a hard limit on long ones.
How do you delete a record from a fixed-record file without shifting the other records?
Mark the record as deleted instead of removing it. Overwrite its one-character status field with D, and the slot keeps its position. Searches and reports skip D slots, and a later add reuses the first one. Physically closing the gap would move every later record and make saved slot numbers wrong.
What goes wrong if a string is longer than its field width when writing a fixed-width record?
An uncut string pushes every later field out of position. A 40-character name written into a 30-wide field shifts the following fields by ten, so that record is longer than the others. Every computed position after it then lands in the wrong place and reads garbage. Pad or cut each field to its exact width before writing.

About the C++ Programming course

How many college credits is C++ Programming?
C++ Programming (Computer Science 242) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does C++ Programming cost and what is included?
$250, paid once, with lifetime access: all 84 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does C++ Programming take?
It is self-paced with no deadlines. The 84 lessons total about 0 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in C++ Programming.

84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

C++ Programming
3 credits · NCCRS
Enroll →