Читаем 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__

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

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

3ds Max 2008
3ds Max 2008

Одни уверены, что нет лучшего способа обучения 3ds Мах, чем прочитать хорошую книгу. Другие склоняются к тому, что эффективнее учиться у преподавателя, который показывает, что и как нужно делать. Данное издание объединяет оба подхода. Его цель – сделать освоение 3ds Мах 2008 максимально быстрым и результативным. Часто после изучения книги у читателя возникают вопросы, почему не получился тот или иной пример. Видеокурс – это гарантия, что такие вопросы не возникнут: ведь автор не только рассказывает, но и показывает, как нужно работать в 3ds Мах.В отличие от большинства интерактивных курсов, где работа в 3ds Мах иллюстрируется на кубиках-шариках, данный видеокурс полностью практический. Все приемы работы с инструментами 3ds Мах 2008 показаны на конкретных примерах, благодаря чему после просмотра курса читатель сможет самостоятельно выполнять даже сложные проекты.

Владимир Антонович Верстак , Владимир Верстак

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