File Read and Write Operations, Explained with Code Examples

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

File Read and Write Operations

C++ Programming · Chapter 9: Structs, Classes, and File StreamsSection 9.9 · lesson 67 of 84video coming soon

← Opening Channels to FilesNext lesson: Applied Challenge: Student Record System →

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

In this lesson

Sending information out, and pulling it in.

  • Write a file layout you can read back
  • Write a reading loop that ends at the right moment
  • Read line by line, and split delimited fields
  • Append safely; tell finishing from failing

Transcript

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

Why Files Matter

Making a Program's Work Outlast the Run

A program that only talks to the screen forgets everything the moment it stops. Writing to a file and reading it back is what makes a program's work outlast the run. The operations for doing it are the ones you already know. The genuinely new material is small: how to write records you'll be able to read back. And how to write a reading loop that stops at the right moment, rather than one record too late.

Familiar Streams

File Streams Behave Like Console Streams

File streams are deliberately built to behave like the streams you've been using since the beginning. An output file stream takes the insertion operator exactly as the screen does. An input file stream takes the extraction operator, and works with getline, exactly as the keyboard does. Almost everything you know transfers unchanged. One difference matters from the start. A file may fail to open at all: a wrong name, a wrong folder, or no permission. So every file stream is checked before it's used.

Writing Records

Designing the File Layout on Output

Here, an output file stream opens books dot txt. If it didn't open, the program says so, and stops. Then each book is written as a title, a comma, the pages, a comma, and the price, followed by a newline. Nothing there is new except the destination. What's new is a responsibility. You're deciding the file's layout, and whoever reads it back, probably you, next week, has to be able to take it apart again. Two decisions do most of the work. One record per line, so a newline reliably means next item. And a separator between fields that can't appear inside a field. A comma is conventional. A space works only if no field ever contains one. Note what the file really holds: the prices are written as 250 and 399, because default formatting drops the trailing zero.

Common Mistake

Unrecoverable Output With No Separator

Write what you can read back. A file written as the title, then the pages, with nothing between them, produces Kanthapura 258, all run together. Here is that file, exactly as it came out. No reading loop can separate that again. The information is all there, and it's unrecoverable, which is a worse position than not having written it. So decide the separator and the record boundary before writing a single line.

Reading Loop

Putting the Read in the Condition

Reading uses the same extraction operator, and the whitespace rules are unchanged. What's new is knowing when to stop, and there's exactly one correct shape. While infile, extracting into score, add score to the total. The read itself is the condition. It's attempted first, and the body runs only if it succeeded. When the file runs out, the attempt fails, the condition is false, and the body doesn't run on that pass. Nothing stale is ever processed. With 10, 20 and 30 in the file, the total is 60. One read per pass, and the loop stops exactly when the data does.

Common Mistake

The End-of-File Loop Adds 30 Twice

Here's the shape that looks right, and isn't: while not infile dot eof, read a score and add it. Take a file holding 10, 20 and 30. The correct loop reads each, runs its body three times, then the fourth read fails, and it stops. The total is 60. The end-of-file loop also reads all three. But after 30 is read successfully, the end-of-file mark is still clear. So the condition is still true, and it goes round once more. That read fails, score keeps 30, and the body adds it a second time. The total is 90. Here is the real output. On an empty file, it's worse: the body runs once, on values that were never read. The correct loop's body never runs, which is right.

Why It Fails

End-of-File Reports a Result, Not a Warning

The reason is precise. The end-of-file mark isn't set when the last value is read: the newline after it is still unread. It's set only when a read runs into the end. So it reports what a read has already found. It's a result, not a warning. It can never tell you in advance that the next read will fail. That's why the read goes in the condition.

Whole Lines

Reading Records With Spaces Using getline

Extraction stops at whitespace, so a record containing spaces, like a title or an address, can't be read with the extraction operator. Read the whole line instead, with getline, and put the read in the condition, for exactly the same reason as before. This loop ends when there's no further line to read, and it never processes a stale one. Run it: both book lines come back whole. It's also the foundation of what comes next. Read one whole line, then take it apart in memory, where mistakes cost nothing.

Splitting Fields

Parsing Lines With String Streams and Conversion

A line such as Kanthapura, 258, 250 holds three fields separated by commas. Read the line, wrap it in a string stream, and use getline with a comma as the delimiter, three times: the title, the pages text, and the price text. Then convert. Stoi turns the pages text into an int, and stod turns the price text into a double. A file stores text and nothing else. The digits 2, 5, 8 are three characters, not the number 258. Numbers are written as digits, and read back as digits. Converting them is a step you always perform, not one you can skip. Run it: adding 1 to the pages, and doubling the price, proves they are real numbers.

Limitation

When a Field Contains the Separator

This simple scheme works precisely as long as no field can contain a comma. A book titled Malgudi Days, Revisited, produces four fields instead of three. Here, the split puts Revisited into the pages field, and the conversion throws. The program stops. Depending on the data, a wrong split can just as easily be silent nonsense. Real formats handle this by quoting fields, or by choosing a separator the data can't contain, such as a tab, or a vertical bar. Know that the limitation exists, and choose a separator your data will never hold.

File Modes

Append Mode Versus Overwriting on Open

Opening a file for writing in the ordinary way empties it immediately. Not on the first write: at the moment of opening. To keep what's there and add to the end, ask for append mode. Here, the log keeps its contents, and run finished is added at the end. Run it twice, and two lines accumulate. An ordinary output stream discards the contents at once. Use it for a file produced from scratch each run, like a report. Append mode keeps them, which suits logs and records accumulated across runs. And an input stream leaves the file untouched. A program that opens its own data file for writing, before checking whether it needed to, has already destroyed it. So open for reading when you only intend to read, and append unless replacing the whole file is what you want.

Error Handling

Telling End of File From Bad Data

The reading loop ends when a read doesn't succeed, and there are two quite different reasons for that. The file ran out, which is normal and expected. Or a record was malformed and couldn't be converted, so the loop stopped partway. The loop itself can't tell you which happened. Asking afterward can. If infile dot eof is true, everything was read, and the file simply ended. Carry on. If it failed without reaching the end, a value couldn't be converted, perhaps letters where a number was expected. Report which record, and decide whether to stop, or skip it. Run it on 10 20 30, then on 10 20 abc 40. The first run read everything. The second stopped at abc, and said so, instead of reporting a wrong total as if it were complete.

Edge Case

Unopened File Looks Like an Empty File

There's one more case, and it's checked before the loop, not after. If the file didn't open, the reading loop runs zero times, and the program reports a total of zero without complaint. That's the same result it would give for a file containing nothing. So the check goes immediately after the open, before any reading. From inside the loop, an unopened file and an empty file are indistinguishable.

Quick Check

No Trailing Newline Changes the Total

Quick check. Run the end-of-file loop again, on a file holding 10, 20 and 30, but with no newline after the 30. What total does it print now? Pause and think. Sixty. Reading 30 runs into the end of the file, so the mark is set at once, and the loop stops after three passes. So that loop's answer depends on how the file happens to end. With the read in the condition, it doesn't matter.

Key Takeaways

Layout, Loop Condition, Conversion, and Append

To summarize. Files use the same operators and getline as the console. Design the layout first: one record per line, with a separator the data can't contain. Put the read in the loop condition, never a test for end of file first. Read whole lines, split them in memory, and convert text to numbers. Append to keep existing data, and check the open before reading anything.

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 File Read and Write Operations

Why does while (!infile.eof()) process the last number twice in C++?
The eof flag is set only after a read runs into the end of the file, so it cannot predict that the next read will fail. If a newline follows the last value, the flag is still clear after 30 is read. The loop runs once more, the read fails, and score keeps 30. A file of 10, 20, 30 then totals 90, not 60.
What is the correct way to write a file reading loop in C++?
Put the read itself in the loop condition, such as while (infile >> score) total += score;. The read is attempted first, and the body runs only if it succeeded. When the data runs out, the read fails and the condition is false, so no stale value is processed. A file holding 10, 20, 30 gives 60.
How do I read a comma-separated line from a file and convert the fields to numbers in C++?
Read the line with getline(infile, line), wrap it in an istringstream, and call getline(ss, field, ',') once per field. Files store only text, so convert the numeric fields afterward with stoi for an int or stod for a double. This breaks if a field itself contains a comma, because the split then produces extra fields.
What is the difference between opening a file with ofstream normally and in append mode in C++?
Opening an ofstream in the ordinary way empties the file at the moment of opening, before any write. Append mode, ios::app, keeps the existing contents and adds new output at the end. Use the ordinary mode for files rebuilt each run, like a report, and append mode for logs or records that accumulate across runs.

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 →