Modern C++ Programming Cookbook
eBook - ePub

Modern C++ Programming Cookbook

Marius Bancila

  1. 590 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Modern C++ Programming Cookbook

Marius Bancila

Book details
Book preview
Table of contents
Citations

About This Book

Over 100 recipes to help you overcome your difficulties with C++ programming and gain a deeper understanding of the working of modern C++About This Bookā€¢ Explore the most important language and library features of C++17, including containers, algorithms, regular expressions, threads, and more, ā€¢ Get going with unit testing frameworks Boost.Test, Google Test and Catch, ā€¢ Extend your C++ knowledge and take your development skills to new heights by making your applications fast, robust, and scalable.Who This Book Is ForIf you want to overcome difficult phases of development with C++ and leverage its features using modern programming practices, then this book is for you. The book is designed for both experienced C++ programmers as well as people with strong knowledge of OOP concepts.What You Will Learnā€¢ Get to know about the new core language features and the problems they were intended to solveā€¢ Understand the standard support for threading and concurrency and know how to put them on work for daily basic tasksā€¢ Leverage C++'s features to get increased robustness and performanceā€¢ Explore the widely-used testing frameworks for C++ and implement various useful patterns and idiomsā€¢ Work with various types of strings and look at the various aspects of compilationā€¢ Explore functions and callable objects with a focus on modern featuresā€¢ Leverage the standard library and work with containers, algorithms, and iteratorsā€¢ Use regular expressions for find and replace string operationsā€¢ Take advantage of the new filesystem library to work with files and directoriesā€¢ Use the new utility additions to the standard library to solve common problems developers encounter including string_view, any, optional and variant typesIn DetailC++ is one of the most widely used programming languages. Fast, efficient, and flexible, it is used to solve many problems. The latest versions of C++ have seen programmers change the way they code, giving up on the old-fashioned C-style programming and adopting modern C++ instead.Beginning with the modern language features, each recipe addresses a specific problem, with a discussion that explains the solution and offers insight into how it works. You will learn major concepts about the core programming language as well as common tasks faced while building a wide variety of software. You will learn about concepts such as concurrency, performance, meta-programming, lambda expressions, regular expressions, testing, and many more in the form of recipes. These recipes will ensure you can make your applications robust and fast.By the end of the book, you will understand the newer aspects of C++11/14/17 and will be able to overcome tasks that are time-consuming or would break your stride while developing.Style and approachThis book follows a recipe-based approach, with examples that will empower you to implement the core programming language features and explore the newer aspects of C++.

Frequently asked questions

Simply head over to the account section in settings and click on ā€œCancel Subscriptionā€ - itā€™s as simple as that. After you cancel, your membership will stay active for the remainder of the time youā€™ve paid for. Learn more here.
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
Both plans give you full access to the library and all of Perlegoā€™s features. The only differences are the price and subscription period: With the annual plan youā€™ll save around 30% compared to 12 months on the monthly plan.
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, weā€™ve got you covered! Learn more here.
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Yes, you can access Modern C++ Programming Cookbook by Marius Bancila in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming Languages. We have over one million books available in our catalogue for you to explore.

Information

Year
2017
ISBN
9781786464736
Edition
1

Working with Files and Streams

The recipes available in this chapter are as follows:
  • Reading and writing raw data from/to binary files
  • Reading and writing objects from/to binary files
  • Using localized settings for streams
  • Using I/O manipulators to control the output of a stream
  • Using monetary I/O manipulators
  • Using time I/O manipulators
  • Working with filesystem paths
  • Creating, copying, and deleting files and directories
  • Removing content from a file
  • Checking the properties of an existing file or directory
  • Enumerating the content of a directory
  • Finding a file

Introduction

One of the most important parts of the C++ standard library is the input/output, stream-based library that enables developers to work with files, memory streams, or other types of I/O devices. The first part of the chapter provides solutions to some common stream operations, such as reading and writing data, localization settings, and manipulating the input and output of a stream. The second part of the chapter explores the new C++17 filesystem library that enables developers to perform operations with the filesystem and its objects, such as files and directories.

Reading and writing raw data from/to binary files

Some of the data programs work with has to be persisted to disk files in various ways, that can include storing it in a database or to flat files, either as text or binary data. This recipe and the next one are focused on persisting and loading both raw data and objects from and to binary files. In this context, raw data means unstructured data, and in this recipe, we will consider writing and reading the content of a buffer (that is, a contiguous sequence of memory, that can be either a C-like array, an std::vector, or an std::array).

Getting ready

For this recipe, you should be familiar with the standard stream input/output library, though some explanations, to the extent required to understand this recipe, are provided below. You should also be familiar with the difference between binary and text files.
In this recipe, we will use the ofstream and ifstream classes, available in the namespace std in the <fstream> header.
In the following examples, we will consider the following data to write to a binary file (and consequently to read back):
 std::vector<unsigned char> output {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; 

How to do it...

To write the content of a buffer (in our example, an std::vector) to a binary file, you should perform the following steps:
  1. Open a file stream for writing in binary mode by creating an instance of the std::ofstream class:
 std::ofstream ofile("sample.bin", std::ios::binary); 
  1. Ensure that the file is actually open before writing data to the file:
 if(ofile.is_open())
{
// streamed file operations
}
  1. Write the data to the file by providing a pointer to the array of characters and the number of characters to write:
 ofile.write(reinterpret_cast<char*>(output.data()), 
output.size());
  1. Flush the content of the stream buffer to the actual disk file; this is automatically done when you close the stream:
 ofile.close(); 
To read the entire content of a binary file to a buffer, you should perform the following steps:
  1. Open a file stream to read from a file in the binary mode by creating an instance of the std::ifstream class:
 std::ifstream ifile("sample.bin", std::ios::binary); 
  1. Ensure that the file is actually opened before reading data from it:
 if(ifile.is_open())
{
// streamed file operations
}
  1. Determine the length of the file by positioning the input position indicator to the end of the file, read its value, and then move the indicator to the beginning:
 ifile.seekg(0, std::ios_base::end);
auto length = ifile.tellg();
ifile.seekg(0, std::ios_base::beg);
  1. Allocate memory to read the content of the file:
 std::vector<unsigned char> input;
input.resize(static_cast<size_t>(length));
  1. Read the content of the file to the allocated buffer by providing a pointer to the array of characters for receiving the data and the number of characters to read:
 ifile.read(reinterpret_cast<char*>(input.data()), length); 
  1. Check that the read operation is completed successfully:
 auto success = !ifile.fail() && length == ifile.gcount(); 
  1. Finally, close the file stream:
 ifile.close(); 

How it works...

The standard stream-based input/output library provides various classes that implement high-level input, output, or both input and output file stream, string stream and character array operations, manipulators that control how these streams behave, and several predefined stream objects (cin/wcin, cout/wcout, cerr/wcerr, and clog/wclog).
These streams are implemented as class templates and, for files, the library provides several classes:
  • basic_filebuf implements the input/output operations for a raw file and is similar in semantics with a C FILE stream.
  • basic_ifstream implements the high-level file stream input operations defined by the basic_istream stream interface, internally using a basic_filebuf object.
  • basic_ofstream implements the high-level file stream output operations defined by the basic_ostream stream interface, internally using a basic_filebuf object.
  • basic_fstream implements the high-level file stream input and output operations defined by the basic_iostream stream interface, internally using a basic_filebuf object.
Several typedefs for the class templates mentioned in the preceding classes are also defined in the <fstream> header. The ofstream and ifstream objects are the type synonyms used in the preceding examples:
 typedef basic_ifstream<char> ifstream;
typedef basic_ifstream<wchar_t> wifstream;
typedef basic_ofstream<char> ofstream;
typedef basic_ofstream<wchar_t> wofstream;
typedef basic_fstream<char> fstream;
typedef basic_fstream<wchar_t> wfstream;
In the previous section, we saw how we can write and read raw data to and from a file stream. The way that works is explained in more detail here:
  • To write data to a file, we instantiated an object of the type std::ofstream. In the constructor, we passed the name of the file to be opened and the stream open mode, for which we specified std::ios::binary to indicate binary mode. Opening the file like this discards the previous file content. If you want to append content to an existing file, you should also use the flag std::ios::app (that is, std::ios::app | std::ios::binary). This constructor internally calls open() on its underlying raw file object, that is, a basic_filebuf object. If this operation fails, a fail bit is set. To check whether the stream has been successfully associated with a file device, we used is_open() (that internally calls the method with the same name from the underlying basic_filebuf). Writing data to the file stream is done with the write() meth...

Table of contents

  1. Title Page
  2. Copyright
  3. Credits
  4. About the Author
  5. About the Reviewer
  6. www.PacktPub.com
  7. Customer Feedback
  8. Preface
  9. Learning Modern Core Language Features
  10. Working with Numbers and Strings
  11. Exploring Functions
  12. Preprocessor and Compilation
  13. Standard Library Containers, Algorithms, and Iterators
  14. General Purpose Utilities
  15. Working with Files and Streams
  16. Leveraging Threading and Concurrency
  17. Robustness and Performance
  18. Implementing Patterns and Idioms
  19. Exploring Testing Frameworks
  20. Bibliography