Читаем C++ Primer Plus полностью

    cout << fixed << right;

// show initial contents

    ifstream fin;

    fin.open(file, ios_base::in |ios_base::binary);  // binary file

    //NOTE: some systems don't accept the ios_base::binary mode

    if (fin.is_open())

    {

    cout << "Here are the current contents of the "

        << file << " file:\n";

    while (fin.read((char *) &pl, sizeof pl))

    {

        cout << setw(20) << pl.name << ": "

              << setprecision(0) << setw(12) << pl.population

              << setprecision(2) << setw(6) << pl.g << endl;

    }

    fin.close();

    }

// add new data

    ofstream fout(file,

             ios_base::out | ios_base::app | ios_base::binary);

    //NOTE: some systems don't accept the ios::binary mode

    if (!fout.is_open())

    {

        cerr << "Can't open " << file << " file for output:\n";

        exit(EXIT_FAILURE);

    }

    cout << "Enter planet name (enter a blank line to quit):\n";

    cin.get(pl.name, 20);

    while (pl.name[0] != '\0')

    {

        eatline();

        cout << "Enter planetary population: ";

        cin >> pl.population;

        cout << "Enter planet's acceleration of gravity: ";

        cin >> pl.g;

        eatline();

        fout.write((char *) &pl, sizeof pl);

        cout << "Enter planet name (enter a blank line "

                "to quit):\n";

        cin.get(pl.name, 20);

    }

    fout.close();

// show revised file

    fin.clear();    // not required for some implementations, but won't hurt

    fin.open(file, ios_base::in | ios_base::binary);

    if (fin.is_open())

    {

        cout << "Here are the new contents of the "

             << file << " file:\n";

        while (fin.read((char *) &pl, sizeof pl))

        {

            cout << setw(20) << pl.name << ": "

                 << setprecision(0) << setw(12) << pl.population

                 << setprecision(2) << setw(6) << pl.g << endl;

        }

        fin.close();

    }

    cout << "Done.\n";

    return 0;

}

Here is a sample initial run of the program in Listing 17.19:

Enter planet name (enter a blank line to quit):

Earth

Enter planetary population: 6928198253

Enter planet's acceleration of gravity: 9.81

Enter planet name (enter a blank line to quit):

Here are the new contents of the planets.dat file:

               Earth:   6928198253  9.81

Done.

And here is a sample follow-up run:

Here are the current contents of the planets.dat file:

               Earth:   6928198253  9.81

Enter planet name (enter a blank line to quit):

Jenny's World

Enter planetary population: 32155648

Enter planet's acceleration of gravity: 8.93

Enter planet name (enter a blank line to quit):

Here are the new contents of the planets.dat file:

               Earth:   6928198253  9.81

       Jenny's World:     32155648  8.93

Done.

You’ve already seen the major features of the program, but let’s re-examine an old point. The program uses this code (in the form of the inline eatline() function) after reading the planet’s g value:

while (std::cin.get() != '\n') continue;

This reads and discards input up through the newline character. Consider the next input statement in the loop:

cin.get(pl.name, 20);

If the newline were left in place, this statement would read the newline as an empty line, terminating the loop.

You might wonder if this program could use a string object instead of a character array for the name member of the planet structure. The answer is no—at least not without major changes in design. The problem is that a string object doesn’t actually contain the string within itself; instead, it contains a pointer to the memory location where the string is stored. So if you copy the structure to a file, you don’t copy the string data, you just copy the address of where the string was stored. When you run the program again, that address is meaningless.

Random Access

For our last file example, let’s look at random access. Random access means moving directly to any location in the file instead of moving through it sequentially. The random access approach is often used with database files. A program will maintain a separate index file, giving the location of data in the main data file. Then it can jump directly to that location, read the data there, and perhaps modify it. This approach is done most simply if the file consists of a collection of equal-sized records. Each record represents a related collection of data. For example, in the example in Listing 17.19, each file record would represent all the data about a particular planet. A file record corresponds rather naturally to a program structure or class.

This example is based on the binary file program in Listing 17.19, to take advantage of the fact that the planet structure provides a pattern for a file record. To add to the creative tension of programming, the example opens the file in a read-and-write mode so that it can both read and modify a record. You can do this by creating an fstream object. The fstream class derives from the iostream class, which, in turn, is based on both the istream and ostream classes, so it inherits the methods of both. It also inherits two buffers, one for input and one for output, and synchronizes the handling of the two buffers. That is, as the program reads the file or writes to it, it moves both an input pointer in the input buffer and an output pointer in the output buffer in tandem.

The example does the following:

1. Displays the current contents of the planets.dat file.

Перейти на страницу:

Все книги серии Developer's Library

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных

Похожие книги

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных