Интересная книга

Стивен Прата
Язык программирования C. Лекции и упражнения
В данной книге очень хорошо и подробно рассмотрен язык. Уделено внимание рассмотрению конкретных примеров. В принципе, эта книга может быть интересно разноуровневым специалистам. Написана известным человеком в данной области. Так что книга "на выходные" есть.
Использование функции _Exit
Для завершения программы без вызова обработчиков, зарегистрированных с помощью функции atexit, можно использовать функцию _Exit. Данная функция задекларирована следующим образом:
void _Exit(int).
В качестве параметра функция принимает код возврата, с которым программа и завершается.
Как я уже упоминал: функции-обработчики не вызываются. Рассмотрим пример кода:
int k=0;
void exit1(){
printf("At function exit1 %d\n",k++);
}
void exit2(){
printf("At function exit2 %d\n",k++);
}
void exit3(){
printf("At function exit3 %d\n",k++);
}
void exit4(){
printf("At function exit4 %d\n", k++);
}
typedef void (* Func_t)(void);
int main (int argc, const char * argv[]) {
Func_t arr[4]={exit1, exit2, exit3, exit4};
int i=0;
for(i=0;i<4;++i)
atexit(arr[i]);
for(i=0;i<10;++i)
if(i==5){
printf("%d",i);
_Exit(0);
}
printf("End of program");
return 0;
}
При выполнении данного кода произойдет следующее. При i==5 программа завершит свое выполнение путем вызова функции _Exit, при этом ни один из обработчиков вызван не будет. Результат выполнения приведен ниже:
[Session started at 2008-11-07 11:10:00 +0300.]
The Debugger has exited with status 0.
Использование функции exit
Первый вариант - это выход при помощи вызова функции exit, которая выглядит следующим образом:
void exit(int)
В качестве параметра в функцию нужно передать код возврата, с которым закончит свою работу программа.
При вызове функции программа завершает свою работу. При этом вызываются все функции, зарегистрированные с помощью функции atexit.
Пример использования:
int k=0;
void exit1(){
printf("At function exit1 %d\n",k++);
}
void exit2(){
printf("At function exit2 %d\n",k++);
}
void exit3(){
printf("At function exit3 %d\n",k++);
}
void exit4(){
printf("At function exit4 %d\n", k++);
}
Это функции - обработчики завершения программы.
typedef void (* Func_t)(void);
int main (int argc, const char * argv[]) {
Func_t arr[4]={exit1, exit2, exit3, exit4};
int i=0;
for(i=0;i<4;++i)
atexit(arr[i]);
for(i=0;i<10;++i)
if(i==5){
printf("%d",i);
exit(0);
}
printf("End of program");
}
При запуске данного кода получаем следующий результат:
5 // Печатается счетчик цикла i
At function exit4 0 // Результат выводится последним обработчиком
At function exit3 1 // Результат выводится предпоследним обработчиком
At function exit2 2 // и т.д.
At function exit1 3
Vacation
Released libgphoto2 2.4.3 in the meantime, polished up my camera page.
Spent the week working on a nice halloween party, role playing with friends, and lots of relaxing, also in a thermal bath. I also worked up libgphoto2, joining the Canon SDK developer program, and integrating some of the documented stuff into libgphoto2.
I'm going to GLUA TechSessions 08
I'll be talking about our magnific BugSquad, Patchsquad, Translators, Gnome Love, my involvment on OSS and Brasero.
Thanks to GLUA members for inviting me for this presentation.
Bootloader gets chattier
Since openSUSE 11.0. we have some basic speech support in our bootloader. This enables visually impaired people to use the bootloader as there is usually no other output device available at that time (BIOS doesn’t really support braille displays).
It uses the PC-speaker for output (which has the benefit that you don’t need specialized sound drivers for every hardware).
If you didn’t try it yet: press F9 at the boot screen.
I’ve reworked that a good deal in openSUSE 11.1 RC1 (2MB sound samples) and now it reads all menus and dialogs to you and spells all chars you enter in input dialogs (actually it speaks the char left from cursor).
The sound samples are pre-generated with espeak. But you are of course free to replace them with your own voice if you like that more. 
Что можно почитать?

Сэмюел П. Харбисон, Гай Л. Стил
Язык программирования C
Книга, а мой взгляд, написана очень хорошо. Полностью раскрыты возможности использования языка, приведены примеры.
Так что, эта книга заслуживает Вашего прочтения.
QJson: a Qt-based library for mapping JSON data to QVariant objects
In order to realize a project of mine I started looking for a Qt library for mapping JSON data to Qt objects.
I came over a couple of solutions but none of them made me happy. So in the last weekend I wrote my own library : QJson The library is based on Qt toolkit and converts JSON data to QVariant instances. JSON arrays will be mapped to QVariantList instances, while JSON’s objects will be mapped to QVariantMap. The JSON parser is generated with Bison, while the scanner has been coded by me.
Usage
Converting JSON’s data to QVariant instance is really simple:
{% codeblock [] [lang:cpp ] %} // create a JSonDriver instance JSonDriver driver; bool ok; // json is a QString containing the data to convert QVariant result = driver.parse (json, &ok); {% endcodeblock %}
Suppose you’re going to convert this JSON data:
{% codeblock [JSON data] [lang:json ] %} { “encoding” : “UTF-8”, “plug-ins” : [ “python”, “c++”, “ruby” ], “indent” : { “length” : 3, “use_space” : true } } {% endcodeblock %}
The following code would convert the JSON data and parse it:
{% codeblock [] [lang:cpp ] %} JSonDriver driver; bool ok; QVariantMap result = driver.parse (json, &ok).toMap(); if (!ok) { qFatal(“An error occured during parsing”); exit (1); } qDebug() << “encoding:” << result[“encoding”].toString(); qDebug() << “plugins:“; foreach (QVariant plugin, result[“plug-ins”].toList()) { qDebug() << “\t-” << plugin.toString(); } QVariantMap nestedMap = result[“indent”].toMap(); qDebug() << “length:” << nestedMap[“length”].toInt(); qDebug() << “use_space:” << nestedMap[“use_space”].toBool(); {% endcodeblock %}
The output would be:
encoding: "UTF-8" plugins: - "python" - "c++" - "ruby" length: 3 use_space: true
Requirements
QJson requires:
- cmake
- Qt
Obtain the source
Actually QJson code is hosted on KDE subversion repository. You can download it using a svn client:
svn co svn://anonsvn.kde.org/home/kde/trunk/playground/libs/qjson
For more informations visit QJson site
Использование atexit
int atexit(void (*)(void)).
Таким образом, функция, которая может использоваться в качестве обработчика выхода из программы, не должна возвращать результатов и, кроме того, она не имеет параметров.
Пример использования:
#include
#include
void exit1(){
printf("At function exit1\n");
}
void exit2(){
printf("At function exit2\n");
}
void exit3(){
printf("At function exit3\n");
}
void exit4(){
printf("At function exit4\n");
}
int main (int argc, const char * argv[]) {
// insert code here...
printf("Hello, World!\n");
atexit(exit1);
atexit(exit2);
atexit(exit3);
atexit(exit4);
int i=0;
for(i=0;i<100;++i)
printf(".");
return 0;
}
[Session started at 2008-11-03 22:45:28 +0300.]
Hello, World!
....................................................................................................At function exit4
At function exit3
At function exit2
At function exit1
Можно зарегистрировать до 32 обработчиков. При этом они будут вызываться в обратном порядке, т.е. последний зарегистрированный обработчик будет вызываться первым.