Читаем Thinking In C++. Volume 2: Practical Programming полностью

<p>A string application</p>

If you’ve looked at the sample code in this book closely, you’ve noticed that certain tokens in the comments surround the code. These are used by a Python program that Bruce wrote to extract the code into files and set up makefiles for building the code. For example, a double-slash followed by a colon at the beginning of a line denotes the first line of a source file. The rest of the line contains information describing the file’s name and location and whether it should be only compiled rather than fully built into an executable file. For example, the first line in the previous program above contains the string C03:IWCompare.cpp, indicating that the file IWCompare.cpp should be extracted into the directory C03.

The last line of a source file contains a triple-slash followed by a colon and a tilde. If the first line has an exclamation point immediately after the colon, the first and last lines of the source code are not to be output to the file (this is for data-only files). (If you’re wondering why we’re avoiding showing you these tokens, it’s because we don’t want to break the code extractor when applied to the text of the book!).

Bruce’s Python program does a lot more than just extract code. If the token "{O}" follows the file name, its makefile entry will only be set up to compile the file and not to link it into an executable. (The Test Framework in Chapter 2 is built this way.) To link such a file with another source example, the target executable’s source file will contain an "{L}" directive, as in.

//{L} ../TestSuite/Test

This section will present a program to just extract all the code so that you can compile and inspect it manually. You can use this program to extract all the code in this book by saving the document file as a text file[36] (let’s call it TICV2.txt) and by executing something like the following on a shell command line:.

C:> extractCode TICV2.txt /TheCode

This command reads the text file TICV2.txt and writes all the source code files in subdirectories under the top-level directory /TheCode. The directory tree will look like the following:

TheCode/

   C0B/

   C01/

   C02/

   C03/

   C04/

   C05/

   C06/

   C07/

   C08/

   C09/

   C10/

   C11/

   TestSuite/

The source files containing the examples from each chapter will be in the corresponding directory.

Here’s the program:

//: C03:ExtractCode.cpp

// Extracts code from text

#include

#include

#include

#include

#include

#include

#include

using namespace std;

// Legacy non-standard C header for mkdir()

#ifdef __GNUC__

#include

#elif defined(__BORLANDC__) || defined(_MSC_VER)

#include

#else

#error Compiler not supported

#endif

// Check to see if directory exists

// by attempting to open a new file

// for output within it.

bool exists(string fname) {

  size_t len = fname.length();

  if(fname[len-1] != '/' && fname[len-1] != '\\')

    fname.append("/");

  fname.append("000.tmp");

  ofstream outf(fname.c_str());

  bool existFlag = outf;

  if (outf) {

    outf.close();

    remove(fname.c_str());

  }

  return existFlag;

}

int main(int argc, char* argv[]) {

  // See if input file name provided

  if(argc == 1) {

    cerr << "usage: extractCode file [dir]\n";

    exit(EXIT_FAILURE);

  }

  // See if input file exists

  ifstream inf(argv[1]);

  if(!inf) {

    cerr << "error opening file: " << argv[1] << endl;

    exit(EXIT_FAILURE);

  }

  // Check for optional output directory

  string root("./");  // current is default

  if(argc == 3) {

    // See if output directory exists

    root = argv[2];

    if(!exists(root)) {

      cerr << "no such directory: " << root << endl;

      exit(EXIT_FAILURE);

    }

    size_t rootLen = root.length();

    if(root[rootLen-1] != '/' && root[rootLen-1] != '\\')

      root.append("/");

  }

  // Read input file line by line

  // checking for code delimiters

  string line;

  bool inCode = false;

  bool printDelims = true;

  ofstream outf;

  while (getline(inf, line)) {

    size_t findDelim = line.find("//" "/:~");

    if(findDelim != string::npos) {

      // Output last line and close file

      if (!inCode) {

        cerr << "Lines out of order\n";

        exit(EXIT_FAILURE);

      }

      assert(outf);

      if (printDelims)

        outf << line << endl;

      outf.close();

      inCode = false;

      printDelims = true;

    } else {

      findDelim = line.find("//" ":");

      if(findDelim == 0) {

        // Check for '!' directive

        if(line[3] == '!') {

          printDelims = false;

          ++findDelim;  // To skip '!' for next search

        }

        // Extract subdirectory name, if any

        size_t startOfSubdir =

          line.find_first_not_of(" \t", findDelim+3);

        findDelim = line.find(':', startOfSubdir);

        if (findDelim == string::npos) {

          cerr << "missing filename information\n" << endl;

          exit(EXIT_FAILURE);

        }

        string subdir;

        if(findDelim > startOfSubdir)

          subdir = line.substr(startOfSubdir,

                findDelim - startOfSubdir);

        // Extract file name (better be one!)

        size_t startOfFile = findDelim + 1;

        size_t endOfFile =

          line.find_first_of(" \t", startOfFile);

        if(endOfFile == startOfFile) {

          cerr << "missing filename\n";

          exit(EXIT_FAILURE);

        }

        // We have all the pieces; build fullPath name

        string fullPath(root);

        if(subdir.length() > 0)

          fullPath.append(subdir).append("/");

        assert(fullPath[fullPath.length()-1] == '/');

        if (!exists(fullPath))

#ifdef __GNUC__

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

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

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

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

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

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

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

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

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