Chapter 8. Working with Files
You now know quite a lot of C++, but there is more to learn. In this chapter, you will work with files, writing them out and reading them back. You’ll generate simulated prices, using the code you wrote in Chapter 7, save them, and learn how to read them back in. You will then have several ways to get prices.
In Chapter 1 you wrote output to a stream, and in Chapter 2 you read input from a stream. Files are also streams in C++, so you know almost everything you need for the project in this chapter. You have also written a function to read a stream, so you’ve done the hard work already. This chapter will show you how to call your get_prices function with a file, rather than with std::cin.
I’ll also discuss how (and why) to return specific values from main, and you will learn about bitwise operators, which are relevant here because a similar idea is used to control files.
Writing to a File
Create a new main.cpp file. You will use the get_prices function from Chapter 7 to generate prices, so include input.h.
Write a function in main called write_to_file to write the generated prices to a file. You previously used std::cout to stream values to the screen. To write to a file in
C++, you use an output file stream, called std::ofstream. This is defined in the <fstream> header. File streams are similar to cout and cin. For example, you use operator << for output.
Try the code in Example 8-1, remembering to add input.cpp to your build.
Example 8-1. Writing ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access