Читаем Linux программирование в примерах полностью

  fprintf(stderr, _("%s: cannot read file: %s\n"),

   argv[0], strerror(errno));

 else

  fprintf(stderr, _("%s: cannot read pipe: %s\n"),

   argv[0], strerror(errno));

Это лучше, чем

if (/* возникла ошибка */) { /* НЕВЕРНО */

 fprintf(stderr, _("%s: cannot read %s: %s\n"), argv[0],

 input_type == INPUT_FILE ? _("file") : _("pipe"),

 strerror(errno));

}

Как только что показано, хорошей мыслью является включение комментария, сообщающего о намеренном использовании нескольких строк, чтобы упростить перевод сообщений.

<p>13.3.8. Создание переводов</p>

После интернационализации программы необходимо подготовить переводы. Это осуществляется с помощью нескольких инструментов уровня оболочки. Мы начнем с интернационализированной версии ch06-echodate.c из раздела 6.1.4 «Преобразование разложенного времени в time_t»:

/* ch13-echodate.c --- демонстрация переводов */

#include

#include

#include

#define ENABLE_NLS 1

#include "gettext.h"

#define _(msgid) gettext(msgid)

#define N_(msgid) msgid

int main (void) {

 struct tm tm;

 time_t then;

 setlocale(LC_ALL, "");

 bindtextdomain("echodate", ".");

 textdomain("echodate");

 printf("%s", _("Enter a Date/time as YYYY/MM/DD HH:MM:SS : "));

 scanf("%d/%d/%d %d:%d:%d",

  &tm.tm_year, &tm.tm_mon, &tm.tm_mday,

  &tm.tm_hour, &tm.tm_min, &tm.tm_sec);

 /* Проверка ошибок для краткости опущена. */

 tm.tm_year -= 1900;

 tm.tm_mon -= 1;

 tm.tm_isdst = -1; /* О летнем времени ничего не известно */

 then = mktime(&tm);

 printf(_("Got: %s"), ctime(&then));

 exit(0);

}

Мы намеренно использовали "gettext.h", а не . Если наше приложение поставляется с отдельной копией библиотеки gettext, тогда "gettext.h" найдет ее, избежав использования системной копии. С другой стороны, если имеется лишь системная копия, она будет найдена, если локальной копии нет. Общеизвестно, что ситуация усложнена фактом наличия на системах Solaris библиотеки gettext, которая не имеет всех возможностей версии GNU.

Переходя к созданию переводов, первым шагом является извлечение переводимых строк. Это осуществляется программой xgettext:

$ xgettext --keyword=_ --keyword=N_ \

> --default-domain=echodate ch13-echodate.с

Опции --keyword сообщает xgettext, что нужно искать макросы _() и N_(). Программа уже знает, как извлекать строки из gettext() и ее вариантов, а также из gettext_noop().

Вывод xgettext называется переносимым объектным файлом. Имя файла по умолчанию messages.ро, что соответствует текстовому домену по умолчанию "messages". Опция --default-domain обозначает текстовый домен для использования в имени выходного файла. В данном случае, файл назван echodate.ро. Вот его содержание:

# SOME DESCRIPTIVE TITLE. /* Шаблон, нужно отредактировать */

# Copyright (С) YEAR THE PACKAGE'S COPYRIGHT HOLDER

# This file is distributed under the same license as the PACKAGE package.

# FIRST AUTHOR , YEAR.

#

#, fuzzy

msgid "" /* Подробная информация */

msgstr "" /* Заполняет каждый переводчик */

"Project-Id-Version: PACKAGE VERSION\n"

"Report-Msgid-Bugs-To: \n"

"POT-Creation-Date: 2003-07-14 18:46-0700\n"

"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"

"Last-Translator: FULL NAME \n"

"Language-Team: LANGUAGE \n"

"MIME-Version: 1.0\n"

"Content-Type: text/plain; charset=CHARSET\n"

"Content-Transfer-Encoding: 8bit\n"

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

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

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

Стивен Прата

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