Bruce Eckel - Thinking In C++. Volume 2 - Practical Programming

Здесь есть возможность читать онлайн «Bruce Eckel - Thinking In C++. Volume 2 - Practical Programming» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Год выпуска: 2003, ISBN: 2003, Издательство: Prentice Hall, Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Thinking In C++. Volume 2: Practical Programming: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Thinking In C++. Volume 2: Practical Programming»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Best selling author Bruce Eckel has joined forces with Chuck Allison to write
, the sequel to the highly received and best selling
. Eckel is the master of teaching professional programmers how to quickly learn cutting edge topics in C++ that are glossed over in other C++ books. In
, the authors cover the finer points of exception handling, defensive programming and string and stream processing that every C++ programmer needs to know. Special attention is given to generic programming where the authors reveal little known techniques for effectively using the Standard Template Library. In addition, Eckel and Allison demonstrate how to apply RTTI, design patterns and concurrent programming techniques to improve the quality of industrial strength C++ applications. This book is targeted at programmers of all levels of experience who want to master C++.

Thinking In C++. Volume 2: Practical Programming — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Thinking In C++. Volume 2: Practical Programming», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Next, you see two output statements that look similar: one to coutand one to the file out. Notice the convenience here; you don’t need to worry about what kind of object you’re dealing with because the formatting statements work the same with all ostreamobjects. The first one echoes the line to standard output, and the second writes the line out to the new file and includes a line number .

To demonstrate getline( ), open the file we just created and strip off the line numbers. To ensure the file is properly closed before opening it to read, you have two choices. You can surround the first part of the program with braces to force the outobject out of scope, thus calling the destructor and closing the file, which is done here. You can also call close( )for both files; if you do this, you can even reuse the inobject by calling the open( )member function .

The second whileloop shows how getline( )removes the terminator character (its third argument, which defaults to '\n') from the input stream when it’s encountered. Although getline( ), like get( ), puts a zero in the buffer, it still doesn’t insert the terminating character .

This example, as well as most of the examples in this chapter, assumes that each call to any overload of getline( )will actually encounter a newline character. If this is not the case, the eofbit state of the stream will be set and the call to getline( )will return false, causing the program to lose the last line of input.

Open modes

You can control the way a file is opened by overriding the constructor’s default arguments. The following table shows the flags that control the mode of the file: .

Flag Function
ios::in Opens an input file. Use this as an open mode for an ofstreamto prevent truncating an existing file.
ios::out Opens an output file. When used for an ofstreamwithout ios::app, ios::ateor ios::in, ios::truncis implied.
ios::app Opens an output file for appending only.
ios::ate Opens an existing file (either input or output) and seeks to the end.
ios::trunc Truncates the old file, if it already exists.
ios::binary Opens a file in binary mode . The default is text mode .

You can combine these flags using a bitwise or operation .

The binary flag, while portable, only has an effect on some non-UNIX systems, such as operating systems derived from MS-DOS, that have special conventions for storing end-of-line delimiters. For example, on MS-DOS systems in text mode (which is the default), every time you output a newline character ( '\n'), the file system actually outputs two characters, a carriage-return/linefeed pair (CRLF), which is the pair of ASCII characters 0x0Dand 0x0A. Conversely, when you read such a file back into memory in text mode, each occurrence of this pair of bytes causes a '\n'to be sent to the program in its place. If you want to bypass this special processing, you open files in binary mode. Binary mode has nothing whatsoever to do with whether you can write raw bytes to a file—you always can (by calling write( )) . You should, however, open a file in binary mode when you’ll be using read( )or write( ), because these functions take a byte count parameter. Having the extra '\r'characters will throw your byte count off in those instances. You should also open a file in binary mode if you’re going to use the stream-positioning commands discussed later in this chapter .

You can open a file for both input and output by declaring an fstreamobject. When declaring an fstreamobject, you must use enough of the open mode flags mentioned earlier to let the file system know whether you want to input, output, or both. To switch from output to input, you need to either flush the stream or change the file position. To change from input to output, change the file position. To create a file via an fstreamobject, you need to use the ios::truncopen mode flag in the constructor call if you will actually do both input and output .

Iostream buffering

Good design practice dictates that whenever you create a new class, you should endeavor to hide the details of the underlying implementation as much possible from the user of the class. You show them only what they need to know and make the rest privateto avoid confusion. When using inserters and extractors, you normally don’t know or care where the bytes are being produced or consumed, whether you’re dealing with standard I/O, files, memory, or some newly created class or device .

A time comes, however, when it is important to communicate with the part of the iostream that produces and consumes bytes. To provide this part with a common interface and still hide its underlying implementation, the standard library abstracts it into its own class, called streambuf. Each iostream object contains a pointer to some kind of streambuf. (The kind depends on whether it deals with standard I/O, files, memory, and so on.) You can access the streambufdirectly; for example, you can move raw bytes into and out of the streambuf, without formatting them through the enclosing iostream. This is accomplished by calling member functions for the streambufobject .

Currently, the most important thing for you to know is that every iostream object contains a pointer to a streambufobject, and the streambufobject has some member functions you can call if necessary. For file and string streams, there are specialized types of stream buffers, as the following figure illustrates .

To allow you to access the streambuf every iostream object has a member - фото 3

To allow you to access the streambuf, every iostream object has a member function called rdbuf( )that returns the pointer to the object’s streambuf. This way you can call any member function for the underlying streambuf. However, one of the most interesting things you can do with the streambufpointer is to connect it to another iostream object using the <<operator. This drains all the characters from your object into the one on the left side of the <<. If you want to move all the characters from one iostream to another, you don’t have to go through the tedium (and potential coding errors) of reading them one character or one line at a time. It’s a much more elegant approach .

For example, here’s a simple program that opens a file and sends the contents to standard output (similar to the previous example): .

//: C04:Stype.cpp

// Type a file to standard output

#include

#include

#include "../require.h"

using namespace std;

int main() {

ifstream in("Stype.cpp");

assure(in, "Stype.cpp");

cout << in.rdbuf(); // Outputs entire file

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Thinking In C++. Volume 2: Practical Programming»

Представляем Вашему вниманию похожие книги на «Thinking In C++. Volume 2: Practical Programming» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Thinking In C++. Volume 2: Practical Programming»

Обсуждение, отзывы о книге «Thinking In C++. Volume 2: Practical Programming» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x