bin/sh - lnduy's blog -

191
LẬP TRÌNH NGUỒN MỞ TS. Lê Nhật Duy Blog: https://Lnduy.wordpress.com Email: [email protected]

Upload: others

Post on 09-Feb-2022

4 views

Category:

Documents


0 download

TRANSCRIPT

LẬP TRÌNH MÃ NGUỒN MỞ

TS. Lê Nhật Duy

Blog: https://Lnduy.wordpress.com

Email: [email protected]

Nội dung chương trình

Mục tiêu môn họcGiúp sinh viên hiểu về lập trình Shell cho Linux,lập trình C/C++ với giao diện trên Linux

Thời lượng Lý thuyết : 30 tiết Thực hành: 30 tiết

Mục tiêu môn họcGiúp sinh viên hiểu về lập trình Shell cho Linux,lập trình C/C++ với giao diện trên Linux

Thời lượng Lý thuyết : 30 tiết Thực hành: 30 tiết

2

Nội dung chương trình

1. Essential Linux

2. Introduction to Linux Programming

3. Shell Programming

4. Graphics Intergace Programming

5. Qt and Databases

6. Development Tools

1. Essential Linux

2. Introduction to Linux Programming

3. Shell Programming

4. Graphics Intergace Programming

5. Qt and Databases

6. Development Tools

3

Kiểm tra đánh giá

Kiểm tra giữa kỳ Tiểu luận theo nhóm Thi kết thúc môn

Kiểm tra giữa kỳ Tiểu luận theo nhóm Thi kết thúc môn

4

Giáo trình và TLTK

Giáo trìnhNeil Matthew, Richard Stones, “Beginning LinuxProgramming”, 4th Edition, Wiley Publishing,Inc, 2008.

Tài liệu tham khảoSlides bài giảng của giảng viên

Giáo trìnhNeil Matthew, Richard Stones, “Beginning LinuxProgramming”, 4th Edition, Wiley Publishing,Inc, 2008.

Tài liệu tham khảoSlides bài giảng của giảng viên

5

Rules

6

Essential Linux

Contents

1. Introduction Linux and Linux Distributions2. Installing Linux3. Getting Help (using man pages, info and other

documentation resources)4. Using Linux Text Editor5. Managing the Linux File System6. Installing and Managing Software on Linux

1. Introduction Linux and Linux Distributions2. Installing Linux3. Getting Help (using man pages, info and other

documentation resources)4. Using Linux Text Editor5. Managing the Linux File System6. Installing and Managing Software on Linux

2

What is Linux ?

Linux is an Unix-like operating system Linux is an free and open source software Linux is a leading server operating system

Multi-user, security, stability, …

3

Linux is an Unix-like operating system Linux is an free and open source software Linux is a leading server operating system

Multi-user, security, stability, …

What is Linux ?

Linux is an operating system,provides key functions in a computer system: Application Platform Hardware Moderator Data Storage Security Connectivity

4

Linux is an operating system,provides key functions in a computer system: Application Platform Hardware Moderator Data Storage Security Connectivity

The History of Linux

GNU/Linux

5

The History of Linux

Richard Matthew Stallman (born March 16, 1953), is anAmerican software freedom activist and computer program Is a student at Harvard University a programmer at the MIT Artificial Intelligence Laboratory

In September 1983, he launched the GNU Project to create afree Unix-like operating system

With the launch of the GNU Project, he initiated the freesoftware movement. In October 1985, he founded the FreeSoftware Foundation, and in 1989 he wrote the GNU GeneralPublic License (GNU GPL)

6

Richard Matthew Stallman (born March 16, 1953), is anAmerican software freedom activist and computer program Is a student at Harvard University a programmer at the MIT Artificial Intelligence Laboratory

In September 1983, he launched the GNU Project to create afree Unix-like operating system

With the launch of the GNU Project, he initiated the freesoftware movement. In October 1985, he founded the FreeSoftware Foundation, and in 1989 he wrote the GNU GeneralPublic License (GNU GPL)

The History of Linux

By the early 1990s, many of the programs required in theGNU project’s operating system (such as libraries,compilers, text editors, a Unix shell, and a windowingsystem) were completed, although low-level elementssuch as device drivers, daemons, and the kernel werestalled and incomplete.

In 1991, in Helsinki, Linus Torvalds began a project thatlater became the Linux kernel Development was done on MINIX using the GNU C compiler

7

By the early 1990s, many of the programs required in theGNU project’s operating system (such as libraries,compilers, text editors, a Unix shell, and a windowingsystem) were completed, although low-level elementssuch as device drivers, daemons, and the kernel werestalled and incomplete.

In 1991, in Helsinki, Linus Torvalds began a project thatlater became the Linux kernel Development was done on MINIX using the GNU C compiler

The History of Linux

The first release of the Linux kernel, Linux 0.01, includeda binary of GNU's Bash shell

In 1992, he suggested releasing the kernel under the GNUGeneral Public License. He first announced this decision in the release notes of version

0.12. In the middle of December 1992 he published version 0.99 using

the GNU GPL

Linux and GNU developers worked to integrate GNUcomponents with Linux to make a fully-functional andfree operating system.

8

The first release of the Linux kernel, Linux 0.01, includeda binary of GNU's Bash shell

In 1992, he suggested releasing the kernel under the GNUGeneral Public License. He first announced this decision in the release notes of version

0.12. In the middle of December 1992 he published version 0.99 using

the GNU GPL

Linux and GNU developers worked to integrate GNUcomponents with Linux to make a fully-functional andfree operating system.

Linux Distributions

A Linux distribution (also called GNU/Linuxdistribution or distro for short ) is a member of thefamily of Unix-like operating systems built on top of the Linux kernel consist a set of libraries and utilities from the GNU

project

9

A Linux distribution (also called GNU/Linuxdistribution or distro for short ) is a member of thefamily of Unix-like operating systems built on top of the Linux kernel consist a set of libraries and utilities from the GNU

project

Linux Distributions ..

Linux distributions have taken a wide variety of forms Commercial or non-commercial; Designed for enterprise users, power users, or for home

users; Supported on multiple types of hardware, or platform-

specific, even to the extent of certification by the platformvendor;

Designed for servers, desktops, or embedded devices; General purpose or highly specialized toward specific

machine functionalities (e.g. firewalls, network routers, andcomputer clusters);

Built primarily for security, usability, portability, orcomprehensiveness.

10

Linux distributions have taken a wide variety of forms Commercial or non-commercial; Designed for enterprise users, power users, or for home

users; Supported on multiple types of hardware, or platform-

specific, even to the extent of certification by the platformvendor;

Designed for servers, desktops, or embedded devices; General purpose or highly specialized toward specific

machine functionalities (e.g. firewalls, network routers, andcomputer clusters);

Built primarily for security, usability, portability, orcomprehensiveness.

Linux Distributions …

Today there are hundreds of differentdistributions available popular■ SUSE Linux ■ TurboLinux■ Fedora Linux ■ Mandrake Linux■ Red Hat Enterprise Linux ■ Lycoris Linux■ Debian Linux■ CentOS ■ Linspire■ ALT Linux■ Gentoo Linux ■ Ubuntu

■Slackware Linux

11

Today there are hundreds of differentdistributions available popular■ SUSE Linux ■ TurboLinux■ Fedora Linux ■ Mandrake Linux■ Red Hat Enterprise Linux ■ Lycoris Linux■ Debian Linux■ CentOS ■ Linspire■ ALT Linux■ Gentoo Linux ■ Ubuntu

■Slackware Linux

Linux Distributions …

12

Roles of Linux

Desktop operating system Server operating system Firewall

13

Desktop operating system Server operating system Firewall

Components of Linux

The Linux Kernel Libraries Utilities User Interface

User

14

The Linux Kernel Libraries Utilities User Interface

User InterfaceLinux Graphical User Interface The Linux GUI is composed of the following components:

X Window System The X Window System provides the base system for the graphical interface on

Linux. It allows programmers to run applications in windows. It also allowsusers to move windows around on the screen as well as click on items with themouse.

Window manager The role of the window manager is to control the appearance of the windows

on the screen. It also determines how they are arranged on the screen. GUI toolkit

GUI toolkits are libraries used by programmers to create X Windowapplications. On Linux, the GTK+, Motif, and Qt toolkits are commonly used.

Desktop environment The desktop environment is used to actually present the GUI desktop to the

end user. It allows you to place icons on the desktop, customize the appearanceof your windows, add wallpaper to the desktop background, and so on. Twovery popular Linux desktop environments include the K Desktop Environment(KDE) and GNOME.

15

The Linux GUI is composed of the following components: X Window System

The X Window System provides the base system for the graphical interface onLinux. It allows programmers to run applications in windows. It also allowsusers to move windows around on the screen as well as click on items with themouse.

Window manager The role of the window manager is to control the appearance of the windows

on the screen. It also determines how they are arranged on the screen. GUI toolkit

GUI toolkits are libraries used by programmers to create X Windowapplications. On Linux, the GTK+, Motif, and Qt toolkits are commonly used.

Desktop environment The desktop environment is used to actually present the GUI desktop to the

end user. It allows you to place icons on the desktop, customize the appearanceof your windows, add wallpaper to the desktop background, and so on. Twovery popular Linux desktop environments include the K Desktop Environment(KDE) and GNOME.

User InterfaceLinux Command-Line Interface (CLI)

The Linux command line interface is created by shells sh (Bourne Shell) bash (Bourne-Again Shell) csh (C Shell) tsch zsh (Z Shell)

The bash shell is the default shell for most distributions A shell is a command interpreter that allows you to type

commands from the keyboard to interact with the operatingsystem kernel.

16

The Linux command line interface is created by shells sh (Bourne Shell) bash (Bourne-Again Shell) csh (C Shell) tsch zsh (Z Shell)

The bash shell is the default shell for most distributions A shell is a command interpreter that allows you to type

commands from the keyboard to interact with the operatingsystem kernel.

Getting Help

Overview

Using the various sources of information to learnabout Linux system.

Include : man utility info utility README files Web-based resources

18

Using the various sources of information to learnabout Linux system.

Include : man utility info utility README files Web-based resources

Using Linux Text Editors

Overview

Use Non-Graphical Linux Text Editors (vi, vim,nano, emacs …)

Graphical Text Editors

20

Overview

Two reasons to learn text manipulation tools Configuration information is stored in a variety of text

files, in the /etc directory Using a text editor to edit these files to customize the

system.$ vi /etc/inittab

21

Two reasons to learn text manipulation tools Configuration information is stored in a variety of text

files, in the /etc directory Using a text editor to edit these files to customize the

system.$ vi /etc/inittab

Using the vi Editor

Two versions of vi vi vim (Vi IMproved)

Replacing vi version on the most newer Linux distributions

Program file locate in /bin When execute the vi program, /usr/bin/vi file called

This is a symbolic link file, points to the /bin/vim executable file

22

Two versions of vi vi vim (Vi IMproved)

Replacing vi version on the most newer Linux distributions

Program file locate in /bin When execute the vi program, /usr/bin/vi file called

This is a symbolic link file, points to the /bin/vim executable file

vi Modes

Switch to Insert modepress I or S or <Insert>

Switch to Replace modepress <Insert>

Switch to Command modepress ESC and press :

Escape current modepress ESC

23

Switch to Command modepress ESC and press :

Escape current modepress ESC

Insert mode Command mode

After starting Vi

Press ESC + :

Press ESC + <insert>

Press Insert Press :

Commands in Command mode

■ w and ENTERWrites the current file

■ w filename and ENTERWrites the current file to a different file name

■ exit and ENTERWrites the current file and then closes vi. Or press wq

■ q Closes vi without saving the current file. This can onlybe used if the file hasn’t been changed. If the file has beenchanged, then you must enter q!

24

■ w and ENTERWrites the current file

■ w filename and ENTERWrites the current file to a different file name

■ exit and ENTERWrites the current file and then closes vi. Or press wq

■ q Closes vi without saving the current file. This can onlybe used if the file hasn’t been changed. If the file has beenchanged, then you must enter q!

Using the Emacs Editor• Emacs is a more powerfultext-based editor• It can use either keyboardcommands or a menu-driveninterface that can bemanipulated with yourmouse.• You will need to install theEmacs package on yourLinux system before you canuse the program.

25

• Emacs is a more powerfultext-based editor• It can use either keyboardcommands or a menu-driveninterface that can bemanipulated with yourmouse.• You will need to install theEmacs package on yourLinux system before you canuse the program.

Use Graphical Text Editors

These editors can only be used if the followingconditions are true:■ The system is working properly.■ The system has X Windows, a window manager, and a desktop

installed.■ Your X Window System has been configured properly to work

with your hardware

Some of graphic editors are : Kate X emacs gedit

26

These editors can only be used if the followingconditions are true:■ The system is working properly.■ The system has X Windows, a window manager, and a desktop

installed.■ Your X Window System has been configured properly to work

with your hardware

Some of graphic editors are : Kate X emacs gedit

Linux File System

The Hierarchical Structure of the LinuxFile System

/root directory

28

home etc

local bin

bin boot dev lib root …usr

Sub directories

/ - The root directory. The starting point of your directorystructure. . Every other file and directory on your system is under the rootdirectory.

/bin - contains shells (bash) and file system managementutilities

/etc - keep linux text-based configuration files /boot - keep important linux booting files /dev - keep all device files /usr - keep all user binary and X library /home - keep user home directory /proc - is pseudo file system for tracking running process and state

of linux system

The Hierarchical Structure of the LinuxFile System

29

/ - The root directory. The starting point of your directorystructure. . Every other file and directory on your system is under the rootdirectory.

/bin - contains shells (bash) and file system managementutilities

/etc - keep linux text-based configuration files /boot - keep important linux booting files /dev - keep all device files /usr - keep all user binary and X library /home - keep user home directory /proc - is pseudo file system for tracking running process and state

of linux system

/var - keeping variable data, log file andprinter spooling

/lib - contain shared library that isrequired by system program

/tmp - contain system temporary file /root - the root user’s home directory /sbin - contains important system management and

admin files (fdisk, fsck, ifconfig, init, mkfs,shutdown, halt)

/media - system use to mount externel devices(CD/DVD , floppy drives) (or /mnt)

The Hierarchical Structure of the LinuxFile System

30

/var - keeping variable data, log file andprinter spooling

/lib - contain shared library that isrequired by system program

/tmp - contain system temporary file /root - the root user’s home directory /sbin - contains important system management and

admin files (fdisk, fsck, ifconfig, init, mkfs,shutdown, halt)

/media - system use to mount externel devices(CD/DVD , floppy drives) (or /mnt)

Navigating the File System

Path absolute path Current directory & relative path

Current directory (.) and parent directory (..) Home directory ( ~ )

31

Path absolute path Current directory & relative path

Current directory (.) and parent directory (..) Home directory ( ~ )

Path /

home etc bin boot dev lib root …usr

a b c /home/a/hoso absolute path

32

Hoso Vd.txt

Vd1.txt

relative path

hoso

a/hoso

home/a/hoso

If current directory

/home/a

/home

/

Current directory and Relative path

pwd, cd pwd (Present Working Directory)

Display the current directory $ pwd

cd Change the current directory $ cd /var/log $ cd .. ( cd ./.. ) $ cd ~ (or press cd )

33

pwd, cd pwd (Present Working Directory)

Display the current directory $ pwd

cd Change the current directory $ cd /var/log $ cd .. ( cd ./.. ) $ cd ~ (or press cd )

Introduction to LinuxProgramming

Contents1. The GNU Project and the Free Software Foundation2. Programming Linux3. The Linux Environment4. Terminals5. Library Functions6. Low-Level File Access7. The Standard I/O Library8. Formatted Input & Output, File & Directories9. The /proc File System

1. The GNU Project and the Free Software Foundation2. Programming Linux3. The Linux Environment4. Terminals5. Library Functions6. Low-Level File Access7. The Standard I/O Library8. Formatted Input & Output, File & Directories9. The /proc File System

2

GNU/Linux

3

GNU - GPL

Tác giả vẫn giữ bản quyền đối với với phần mềm gốc. Người sử dụng có quyền :

Tự do chạy chương trình, cho bất cứ mục đích nào. Tự do tái phân phối bản sao. Tự do tìm hiểu cách hoạt động của chương trình, tự do sửa đổi

nó và phát hành những gì sửa đổi ra công cộng. Người sử dụng có thể thay đổi một phần của chương trình và phân

phối thay đổi của mình cùng toàn bộ phần mềm cho người khác,với điều kiện nói rõ phần mình thay đổi.

Phải đảm bảo cung cấp mã nguồn khi bán một sản phẩm theoGNU GPL để người khác có thể sử dụng và/hoặc bán tiếp. Ngườidùng kế tiếp có đầy đủ quyền lợi như của người trước.

4

Tác giả vẫn giữ bản quyền đối với với phần mềm gốc. Người sử dụng có quyền :

Tự do chạy chương trình, cho bất cứ mục đích nào. Tự do tái phân phối bản sao. Tự do tìm hiểu cách hoạt động của chương trình, tự do sửa đổi

nó và phát hành những gì sửa đổi ra công cộng. Người sử dụng có thể thay đổi một phần của chương trình và phân

phối thay đổi của mình cùng toàn bộ phần mềm cho người khác,với điều kiện nói rõ phần mình thay đổi.

Phải đảm bảo cung cấp mã nguồn khi bán một sản phẩm theoGNU GPL để người khác có thể sử dụng và/hoặc bán tiếp. Ngườidùng kế tiếp có đầy đủ quyền lợi như của người trước.

Programming Linux List of programming languages available to the Linux

programmer:

5

Linux Programs

Linux applications are represented by two specialtypes of files: executables and scripts.Executable files are programs that can be rundirectly by the computer; they correspond toWindows .exe files. Scripts are collections ofinstructions for another program, an interpreter, tofollow. These correspond to Windows .bat or.cmd files, or interpreted BASIC programs.

Linux applications are represented by two specialtypes of files: executables and scripts.Executable files are programs that can be rundirectly by the computer; they correspond toWindows .exe files. Scripts are collections ofinstructions for another program, an interpreter, tofollow. These correspond to Windows .bat or.cmd files, or interpreted BASIC programs.

6

The First Linux C Program#include <stdio.h>#include <stdlib.h>int main(){

printf(“Hello World\n”);exit(0);

}gcc -o hello hello.c./hello

#include <stdio.h>#include <stdlib.h>int main(){

printf(“Hello World\n”);exit(0);

}gcc -o hello hello.c./hello

7

Static Libraries

// file fred.c#include <stdio.h>void fred(int arg){

printf(“fred: wepassed %d\n”, arg);

}

gcc -c bill.c fred.c

//file bill.c#include <stdio.h>void bill(char *arg){

printf(“bill: wepassed %s\n”, arg);

}

// file fred.c#include <stdio.h>void fred(int arg){

printf(“fred: wepassed %d\n”, arg);

}

gcc -c bill.c fred.c

//file bill.c#include <stdio.h>void bill(char *arg){

printf(“bill: wepassed %s\n”, arg);

}

8

Compile the program and test it

#include <stdlib.h>#include “lib.h”int main(){

bill(“Hello World”);exit(0);

}gcc -c program.cgcc -o program program.o bill.o./program

#include <stdlib.h>#include “lib.h”int main(){

bill(“Hello World”);exit(0);

}gcc -c program.cgcc -o program program.o bill.o./program

9

Libraries (cont.)

Create and use a library. Use the ar program tocreate the archive and add your object files to it.The program is called ar because it createsarchives, or collections, of individual files placedtogether in one large file. Note that we can alsouse ar to create archives of files of any type.

$ ar crv libfoo.a bill.o fred.oa - bill.oa - fred.o

Create and use a library. Use the ar program tocreate the archive and add your object files to it.The program is called ar because it createsarchives, or collections, of individual files placedtogether in one large file. Note that we can alsouse ar to create archives of files of any type.

$ ar crv libfoo.a bill.o fred.oa - bill.oa - fred.o

10

Libraries (cont.)

To use the library successfully, some systems,notably those derived from Berkeley UNIX,require that a table of contents be created for thelibrary. Do this with the ranlib command. InLinux, this step isn’t necessary when you’re usingthe GNU software development tools.

$ ranlib libfoo.a$ gcc -o program program.o libfoo.a$ ./program

To use the library successfully, some systems,notably those derived from Berkeley UNIX,require that a table of contents be created for thelibrary. Do this with the ranlib command. InLinux, this step isn’t necessary when you’re usingthe GNU software development tools.

$ ranlib libfoo.a$ gcc -o program program.o libfoo.a$ ./program

11

12

Shared Libraries

One disadvantage of static libraries is that whenyou run many applications at the same time andthey all use functions from the same library, youmay end up with many copies of the samefunctions in memory and indeed many copies inthe program files themselves. This can consume alarge amount of valuable memory and disk space.

One disadvantage of static libraries is that whenyou run many applications at the same time andthey all use functions from the same library, youmay end up with many copies of the samefunctions in memory and indeed many copies inthe program files themselves. This can consume alarge amount of valuable memory and disk space.

13

Share …

Many UNIX systems and Linux-support sharedlibraries can overcome this disadvantage. A completediscussion of shared libraries and theirimplementation on different systems is beyond thescope of this book, so we’ll restrict ourselves to thevisible implementation under Linux. Shared librariesare stored in the same places as static libraries, butshared libraries have a different filename suffix. On atypical Linux system, the shared version of thestandard math library is /lib/libm.so.

Many UNIX systems and Linux-support sharedlibraries can overcome this disadvantage. A completediscussion of shared libraries and theirimplementation on different systems is beyond thescope of this book, so we’ll restrict ourselves to thevisible implementation under Linux. Shared librariesare stored in the same places as static libraries, butshared libraries have a different filename suffix. On atypical Linux system, the shared version of thestandard math library is /lib/libm.so.

14

Shell Programming

Contents❑What a shell is❑ Basic considerations❑ The subtleties of syntax: variables, conditions, and

program control❑ Lists❑ Functions❑ Commands and command execution❑ Here documents❑ Debugging❑ grep and regular expressions❑ find

❑What a shell is❑ Basic considerations❑ The subtleties of syntax: variables, conditions, and

program control❑ Lists❑ Functions❑ Commands and command execution❑ Here documents❑ Debugging❑ grep and regular expressions❑ find

2

What Is a Shell?

A shell is a programthat acts as the interfacebetween you and theLinux system, enablingyou to enter commandsfor the operating systemto execute.

A shell is a programthat acts as the interfacebetween you and theLinux system, enablingyou to enter commandsfor the operating systemto execute.

3

Shell …

On Linux, the standard shell that is alwaysinstalled as /bin/sh is called bash (the GNUBourne-Again SHell). On most Linuxdistributions, the program /bin/sh, the defaultshell, is actually a link to the program /bin/bash.

/bin/bash --version

On Linux, the standard shell that is alwaysinstalled as /bin/sh is called bash (the GNUBourne-Again SHell). On most Linuxdistributions, the program /bin/sh, the defaultshell, is actually a link to the program /bin/bash.

/bin/bash --version

4

5

Pipes and Redirection

Redirecting Output $ ls -l > lsoutput.txt To append to the file, use the >> operator. For

example, $ ps >> lsoutput.txt will append theoutput of the ps command to the end of thespecified file.

Redirecting Output $ ls -l > lsoutput.txt To append to the file, use the >> operator. For

example, $ ps >> lsoutput.txt will append theoutput of the ps command to the end of thespecified file.

6

Redirecting Input

Rather like redirecting output, you can alsoredirect input

$ more < killout.txt

7

Pipes - the pipe operator ( | )

In Linux, unlike in MS-DOS, processes connectedby pipes can run simultaneously and areautomatically rescheduled as data flows betweenthem.

sort psout.txt > sort.out

In Linux, unlike in MS-DOS, processes connectedby pipes can run simultaneously and areautomatically rescheduled as data flows betweenthem.

sort psout.txt > sort.out

8

The Shell as a Programming Language

# Creating a Script first#!/bin/bash (or #!/bin/sh)for file in *doif grep -q POSIX $filethenecho $filefidoneexit 0

Making a ScriptExecutable

1. $ /bin/sh first2. $ chmod +x first

$ first

# Creating a Script first#!/bin/bash (or #!/bin/sh)for file in *doif grep -q POSIX $filethenecho $filefidoneexit 0

Making a ScriptExecutable

1. $ /bin/sh first2. $ chmod +x first

$ first

9

The Shell ..

The command wasn’t found??? This is almostcertainly because the shell environment variablePATH isn’t set to look in the current directory forcommands to execute. To change this, either typePATH=$PATH: . on the command line or edityour .bash_profile file to add this command tothe end of the file; then log out and log back inagain. Alternatively, type ./first in the directorycontaining the script, to give the shell the fullrelative path to the file

The command wasn’t found??? This is almostcertainly because the shell environment variablePATH isn’t set to look in the current directory forcommands to execute. To change this, either typePATH=$PATH: . on the command line or edityour .bash_profile file to add this command tothe end of the file; then log out and log back inagain. Alternatively, type ./first in the directorycontaining the script, to give the shell the fullrelative path to the file

10

Cont …

In Linux you can delete a file if you have writepermission on the directory that contains it. To besafe, ensure that only the superuser can write todirectories containing files that you want to keepsafe. This makes sense because a directory is justanother file, and having write permission to adirectory file allows users to add and removenames.

# chmod u=rwx,go=rx /usr/local/bin/first

In Linux you can delete a file if you have writepermission on the directory that contains it. To besafe, ensure that only the superuser can write todirectories containing files that you want to keepsafe. This makes sense because a directory is justanother file, and having write permission to adirectory file allows users to add and removenames.

# chmod u=rwx,go=rx /usr/local/bin/first

11

Shell Syntax

Variables: strings, numbers, environments, andparameters

Conditions: shell Booleans Program control: if, elif, for, while, until, case Lists Functions Commands built into the shell Getting the result of a command Here documents

Variables: strings, numbers, environments, andparameters

Conditions: shell Booleans Program control: if, elif, for, while, until, case Lists Functions Commands built into the shell Getting the result of a command Here documents

12

Variables#!/bin/shmyvar=”Hi there”echo $myvarecho “$myvar”echo ‘$myvar’echo \$myvarecho Enter some textread myvarecho ‘$myvar’ now equals $myvarexit 0

#!/bin/shmyvar=”Hi there”echo $myvarecho “$myvar”echo ‘$myvar’echo \$myvarecho Enter some textread myvarecho ‘$myvar’ now equals $myvarexit 0

13

Environment Variables

14

Parameter Variables

15

Manipulating Parameter and Environment Variables

#!/bin/shsalutation=”Hello”echo $salutationecho “The program $0 is now running”echo “The second parameter was $2”echo “The first parameter was $1”echo “The parameter list was $*“echo “The user’s home directory is $HOME”echo “Please enter a new greeting”read salutationecho $salutationecho “The script is now complete”exit 0

#!/bin/shsalutation=”Hello”echo $salutationecho “The program $0 is now running”echo “The second parameter was $2”echo “The first parameter was $1”echo “The parameter list was $*“echo “The user’s home directory is $HOME”echo “Please enter a new greeting”read salutationecho $salutationecho “The script is now complete”exit 0 16

Conditions

The test or [ Commandif test -f fred.cthen...fi

if [ -f fred.c ]then...fi------------------------------if [ -f fred.c ]; then...fi

The test or [ Commandif test -f fred.cthen...fi

if [ -f fred.c ]then...fi------------------------------if [ -f fred.c ]; then...fi

17

The condition types that you can use with the test commandfall into three types: string comparison, arithmeticcomparison, and file conditionals. The following tabledescribes these condition types:

18

19

20

Control Structures#!/bin/shecho “Is it morning? Please answer yes or no”read timeofdayif [ $timeofday = “yes” ]thenecho “Good morning”elif [ $timeofday = “no” ]; thenecho “Good afternoon”elseecho “Sorry, $timeofday not recognized. Enter yes or no”exit 1fiexit 0

#!/bin/shecho “Is it morning? Please answer yes or no”read timeofdayif [ $timeofday = “yes” ]thenecho “Good morning”elif [ $timeofday = “no” ]; thenecho “Good afternoon”elseecho “Sorry, $timeofday not recognized. Enter yes or no”exit 1fiexit 0

21

for

for variable in valuesdostatementsdone

#!/bin/shfor foo in bar fud 43doecho $foodoneexit 0

for variable in valuesdostatementsdone

#!/bin/shfor foo in bar fud 43doecho $foodoneexit 0

22

while

while condition dostatementsdone

#!/bin/shecho “Enter password”read trythiswhile [ “$trythis” !=

“secret” ]; doecho “Sorry, try again”read trythisdoneexit 0

#!/bin/shecho “Enter password”read trythiswhile [ “$trythis” !=

“secret” ]; doecho “Sorry, try again”read trythisdoneexit 0

23

until

until conditiondostatementsdone

#!/bin/bashuntil who | grep “$1” > /dev/nulldosleep 60done# now ring the bell and announce

the expected user.echo -e ‘\a’echo “**** $1 has just logged in

****“exit 0

until conditiondostatementsdone

#!/bin/bashuntil who | grep “$1” > /dev/nulldosleep 60done# now ring the bell and announce

the expected user.echo -e ‘\a’echo “**** $1 has just logged in

****“exit 0

24

case

case variable inpattern [ | pattern] ...)

statements;;pattern [ | pattern] ...)

statements;;...esac

#!/bin/shecho “Is it morning? Please

answer yes or no”read timeofdaycase “$timeofday” inyes) echo “Good Morning”;;no ) echo “Good Afternoon”;;y ) echo “Good Morning”;;n ) echo “Good Afternoon”;;* ) echo “Sorry, answer not

recognized”;;esacexit 0

case variable inpattern [ | pattern] ...)

statements;;pattern [ | pattern] ...)

statements;;...esac

#!/bin/shecho “Is it morning? Please

answer yes or no”read timeofdaycase “$timeofday” inyes) echo “Good Morning”;;no ) echo “Good Afternoon”;;y ) echo “Good Morning”;;n ) echo “Good Afternoon”;;* ) echo “Sorry, answer not

recognized”;;esacexit 0

25

Lists

if [ -f this_file ]; thenif [ -f that_file ]; thenif [ -f the_other_file ]; thenecho “All files present, and correct”fififi

if [ -f this_file ]; thenif [ -f that_file ]; thenif [ -f the_other_file ]; thenecho “All files present, and correct”fififi

26

The AND Liststatement1 && statement2 && statement3 && ...#!/bin/shtouch file_onerm -f file_twoif [ -f file_one ] && echo “hello” && [ -f file_two ] && echo “

there”thenecho “in if”elseecho “in else”fiexit 0

statement1 && statement2 && statement3 && ...#!/bin/shtouch file_onerm -f file_twoif [ -f file_one ] && echo “hello” && [ -f file_two ] && echo “

there”thenecho “in if”elseecho “in else”fiexit 0

27

The OR List

statement1 || statement2 || statement3 || ...#!/bin/shrm -f file_oneif [ -f file_one ] || echo “hello” || echo “ there”thenecho “in if”elseecho “in else”fiexit 0

statement1 || statement2 || statement3 || ...#!/bin/shrm -f file_oneif [ -f file_one ] || echo “hello” || echo “ there”thenecho “in if”elseecho “in else”fiexit 0

28

Functionsfunction_name () {statements}-------------------------------------------------------------#!/bin/shfoo() {echo “Function foo is executing”}echo “script starting”fooecho “script ended”exit 0

function_name () {statements}-------------------------------------------------------------#!/bin/shfoo() {echo “Function foo is executing”}echo “script starting”fooecho “script ended”exit 0 29

break#!/bin/shrm -rf fred*echo > fred1echo > fred2mkdir fred3echo > fred4for file in fred*doif [ -d “$file” ]; thenbreak;fidoneecho first directory starting fred was $filerm -rf fred*exit 0

#!/bin/shrm -rf fred*echo > fred1echo > fred2mkdir fred3echo > fred4for file in fred*doif [ -d “$file” ]; thenbreak;fidoneecho first directory starting fred was $filerm -rf fred*exit 0 30

The : Command

The colon command is a null command. It’soccasionally useful to simplify the logic ofconditions, being an alias for true. Since it’s built-in, :runs faster than true, though its output is also muchless readable. You may see it used as a condition forwhile loops; while : implements an infinite loop inplace of the more common while true. The : constructis also useful in the conditional setting of variables.For example,

: ${var:=value} Without the :, the shell would try toevaluate $var as a command.

The colon command is a null command. It’soccasionally useful to simplify the logic ofconditions, being an alias for true. Since it’s built-in, :runs faster than true, though its output is also muchless readable. You may see it used as a condition forwhile loops; while : implements an infinite loop inplace of the more common while true. The : constructis also useful in the conditional setting of variables.For example,

: ${var:=value} Without the :, the shell would try toevaluate $var as a command.

31

Exam…

#!/bin/shrm -f fredif [ -f fred ]; then:elseecho file fred did not existfiexit 0

#!/bin/shrm -f fredif [ -f fred ]; then:elseecho file fred did not existfiexit 0

32

continue

Rather like the C statement of the same name, thiscommand makes the enclosing for, while, or untilloop continue at the next iteration, with the loopvariable taking the next value in the list:

Rather like the C statement of the same name, thiscommand makes the enclosing for, while, or untilloop continue at the next iteration, with the loopvariable taking the next value in the list:

33

continue

#!/bin/shrm -rf fred*echo > fred1echo > fred2mkdir fred3echo > fred4

for file in fred*doif [ -d “$file” ]; thenecho “skipping directory $file”continuefiecho file is $filedonerm -rf fred*exit 0

#!/bin/shrm -rf fred*echo > fred1echo > fred2mkdir fred3echo > fred4

for file in fred*doif [ -d “$file” ]; thenecho “skipping directory $file”continuefiecho file is $filedonerm -rf fred*exit 0

34

The . Command

The dot (.) command executes the command inthe current shell:

. ./shell_script#!/bin/shversion=classicPATH=/usr/local/old_bin:/usr/bin:/bin:.PS1=”classic> “

The dot (.) command executes the command inthe current shell:

. ./shell_script#!/bin/shversion=classicPATH=/usr/local/old_bin:/usr/bin:/bin:.PS1=”classic> “

35

echo

Despite the X/Open exhortation to use the printfcommand in modern shells, we’ve been followingcommon practice by using the echo command tooutput a string followed by a newline character.

echo -n “string to output” echo -e “string to output\c”

Despite the X/Open exhortation to use the printfcommand in modern shells, we’ve been followingcommon practice by using the echo command tooutput a string followed by a newline character.

echo -n “string to output” echo -e “string to output\c”

36

eval

The eval commandenables you to evaluatearguments. It’s built intothe shell and doesn’tnormally exist as aseparate command. It’sprobably bestdemonstrated with a shortexample borrowed fromthe X/Open specificationitself:

foo=10x=fooy=’$’$xecho $y

foo=10x=foo

eval y=’$’$xecho $y

The eval commandenables you to evaluatearguments. It’s built intothe shell and doesn’tnormally exist as aseparate command. It’sprobably bestdemonstrated with a shortexample borrowed fromthe X/Open specificationitself:

foo=10x=fooy=’$’$xecho $y

foo=10x=foo

eval y=’$’$xecho $y

37

exec

The exec command has two different uses. Its typical useis to replace the current shell with a different program.For example,

exec wall “Thanks for all the fish” in a script will replace the current shell with the wall

command. The second use of exec is to modify the current file

descriptors: exec 3< afile This causes file descriptor three to be opened for reading

from file afile.

The exec command has two different uses. Its typical useis to replace the current shell with a different program.For example,

exec wall “Thanks for all the fish” in a script will replace the current shell with the wall

command. The second use of exec is to modify the current file

descriptors: exec 3< afile This causes file descriptor three to be opened for reading

from file afile.38

exit n

In shell script programming, exitcode 0 is success, and codes 1through 125, inclusive, are errorcodes that can be used by scripts.

39

export

The export command makes the variable named as itsparameter available in subshells. By default,variables created in a shell are not available in further(sub)shells invoked from that shell. The exportcommand creates an environment variable from itsparameter that can be seen by other scripts andprograms invoked from the current program. Moretechnically, the exported variables form theenvironment variables in any child processes derivedfrom the shell. This is best illustrated with anexample of two scripts, export1 and export2.

The export command makes the variable named as itsparameter available in subshells. By default,variables created in a shell are not available in further(sub)shells invoked from that shell. The exportcommand creates an environment variable from itsparameter that can be seen by other scripts andprograms invoked from the current program. Moretechnically, the exported variables form theenvironment variables in any child processes derivedfrom the shell. This is best illustrated with anexample of two scripts, export1 and export2.

40

Exam…

First, list export2:#!/bin/shecho “$foo”echo “$bar”

Now for export1. At the endof this script, invoke export2

#!/bin/shfoo=”The first meta-syntactic

variable”export bar=”The second

meta-syntactic variable”export2 ./export1

First, list export2:#!/bin/shecho “$foo”echo “$bar”

Now for export1. At the endof this script, invoke export2

#!/bin/shfoo=”The first meta-syntactic

variable”export bar=”The second

meta-syntactic variable”export2 ./export1

41

expr

The expr command evaluates its arguments as anexpression. It’s most commonly used for simplearithmetic in the following form:

x=`expr $x + 1`

The expr command evaluates its arguments as anexpression. It’s most commonly used for simplearithmetic in the following form:

x=`expr $x + 1`

42

43

printf

The syntax is printf “format string“ parameter1 parameter2

...

The syntax is printf “format string“ parameter1 parameter2

...

44

$ printf “%s\n” hellohello$ printf “%s %d\t%s” “Hi There” 15 peopleHi There 15 people

45

return

The return command causes functions to return,as mentioned when we looked at functions earlier.return takes a single numeric parameter that isavailable to the script calling the function. If noparameter is specified, then return defaults to theexit code of the last command.

The return command causes functions to return,as mentioned when we looked at functions earlier.return takes a single numeric parameter that isavailable to the script calling the function. If noparameter is specified, then return defaults to theexit code of the last command.

46

set

The set command sets the parameter variables forthe shell. It can be a useful way of using fields incommands that output space-separated values.

#!/bin/shecho the date is $(date)set $(date)echo The month is $2exit 0

The set command sets the parameter variables forthe shell. It can be a useful way of using fields incommands that output space-separated values.

#!/bin/shecho the date is $(date)set $(date)echo The month is $2exit 0

47

shift

The shift command moves all the parametervariables down by one, so that $2 becomes $1, $3becomes $2, and so on. The previous value of $1is discarded, while $0 remains unchanged. If anumerical parameter is specified in the call toshift, the parameters move that many spaces. Theother variables, $*, $@, and $#, are also modifiedin line with the new arrangement of parametervariables.

The shift command moves all the parametervariables down by one, so that $2 becomes $1, $3becomes $2, and so on. The previous value of $1is discarded, while $0 remains unchanged. If anumerical parameter is specified in the call toshift, the parameters move that many spaces. Theother variables, $*, $@, and $#, are also modifiedin line with the new arrangement of parametervariables.

48

shift

shift is often useful forscanning throughparameters passed into ascript, and if your scriptrequires 10 or moreparameters, you’ll needshift to access the tenthand beyond.

#!/bin/shwhile [ “$1” != “” ]; doecho “$1”shiftdoneexit 0

shift is often useful forscanning throughparameters passed into ascript, and if your scriptrequires 10 or moreparameters, you’ll needshift to access the tenthand beyond.

#!/bin/shwhile [ “$1” != “” ]; doecho “$1”shiftdoneexit 0

49

trap

The trap command is used to specify the actions to takeon receipt of signals, which you’ll meet in more detaillater in the book. A common use is to tidy up a scriptwhen it is interrupted.

trap command signal

The trap command is used to specify the actions to takeon receipt of signals, which you’ll meet in more detaillater in the book. A common use is to tidy up a scriptwhen it is interrupted.

trap command signal

50

unset

The unset command removes variables orfunctions from the environment. It can’t do this toread-only variables defined by the shell itself,such as IFS. It’s not often used.

#!/bin/shfoo=”Hello World”echo $foounset fooecho $foo

The unset command removes variables orfunctions from the environment. It can’t do this toread-only variables defined by the shell itself,such as IFS. It’s not often used.

#!/bin/shfoo=”Hello World”echo $foounset fooecho $foo

51

The find Command

find / -name test –print The grep Command find / -name test –print The grep Command

52

Debugging Scripts

53

Going Graphical — The dialog Utility

The whole idea of dialog is beautifully simple — asingle program with a variety of parameters andoptions that allows you to display various types ofgraphical boxes, ranging from simple Yes/No boxesto input boxes and even menu selections. The utilitygenerally returns when the user has made some sortof input, and the result can be found either from theexit status or if text was entered by retrieving thestandard error stream.

dialog --msgbox “Hello World” 9 18

The whole idea of dialog is beautifully simple — asingle program with a variety of parameters andoptions that allows you to display various types ofgraphical boxes, ranging from simple Yes/No boxesto input boxes and even menu selections. The utilitygenerally returns when the user has made some sortof input, and the result can be found either from theexit status or if text was entered by retrieving thestandard error stream.

dialog --msgbox “Hello World” 9 18

54

dialog

55

56

Working with Files

Contents1. ❑ Files and devices2. ❑ System calls3. ❑ Library functions4. ❑ Low-level file access5. ❑Managing files6. ❑ The standard I/O library7. ❑ Formatted input and output8. ❑ File and directory maintenance9. ❑ Scanning directories10. ❑ Errors11. ❑ The /proc file system12. ❑ Advanced topics: fcntl and mmap

1. ❑ Files and devices2. ❑ System calls3. ❑ Library functions4. ❑ Low-level file access5. ❑Managing files6. ❑ The standard I/O library7. ❑ Formatted input and output8. ❑ File and directory maintenance9. ❑ Scanning directories10. ❑ Errors11. ❑ The /proc file system12. ❑ Advanced topics: fcntl and mmap

2

Directories

3

Files and Devices

# mount -t iso9660 /dev/hdc /mnt/cdrom # cd /mnt/cdrom

4

System Calls and Device Drivers

The low-level functions used to access the devicedrivers, the system calls, include:❑ open: Open a file or device❑ read: Read from an open file or device❑ write: Write to a file or device❑ close: Close the file or device❑ ioctl: Pass control information to a device driver

The low-level functions used to access the devicedrivers, the system calls, include:❑ open: Open a file or device❑ read: Read from an open file or device❑ write: Write to a file or device❑ close: Close the file or device❑ ioctl: Pass control information to a device driver

5

Library Functions

6

Low-Level File Access

Each running program, called a process, has a numberof file descriptors associated with it. These are smallintegers that you can use to access open files ordevices. How many of these are available will varydepending on how the system has been configured.When a program starts, it usually has three of thesedescriptors already opened. These are:❑ 0: Standard input❑ 1: Standard output❑ 2: Standard error

Each running program, called a process, has a numberof file descriptors associated with it. These are smallintegers that you can use to access open files ordevices. How many of these are available will varydepending on how the system has been configured.When a program starts, it usually has three of thesedescriptors already opened. These are:❑ 0: Standard input❑ 1: Standard output❑ 2: Standard error

7

write

#include <unistd.h> size_t write(int fildes, const void *buf, size_t nbytes); #include <unistd.h> size_t write(int fildes, const void *buf, size_t nbytes);

8

write

The write system call arranges for the first nbytesbytes from buf to be written to the file associatedwith the file descriptor fildes. It returns thenumber of bytes actually written. This may be lessthan nbytes if there has been an error in the filedescriptor or if the underlying device driver issensitive to block size. If the function returns 0, itmeans no data was written; if it returns –1, therehas been an error in the write call, and the errorwill be specified in the errno global variable.

The write system call arranges for the first nbytesbytes from buf to be written to the file associatedwith the file descriptor fildes. It returns thenumber of bytes actually written. This may be lessthan nbytes if there has been an error in the filedescriptor or if the underlying device driver issensitive to block size. If the function returns 0, itmeans no data was written; if it returns –1, therehas been an error in the write call, and the errorwill be specified in the errno global variable.

9

read The read system call reads up to nbytes bytes of

data from the file associated with the filedescriptor fildes and places them in the data areabuf. It returns the number of data bytes actuallyread, which may be less than the numberrequested. If a read call returns 0, it had nothingto read; it reached the end of the file. Again, anerror on the call will cause it to return –1.

#include <unistd.h> size_t read(int fildes, void *buf, size_t nbytes);

The read system call reads up to nbytes bytes ofdata from the file associated with the filedescriptor fildes and places them in the data areabuf. It returns the number of data bytes actuallyread, which may be less than the numberrequested. If a read call returns 0, it had nothingto read; it reached the end of the file. Again, anerror on the call will cause it to return –1.

#include <unistd.h> size_t read(int fildes, void *buf, size_t nbytes);

10

11

open

To create a new file descriptor, you need to usethe open system call.

#include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> int open(const char *path, int oflags); int open(const char *path, int oflags, mode_t mode);

To create a new file descriptor, you need to usethe open system call.

#include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> int open(const char *path, int oflags); int open(const char *path, int oflags, mode_t mode);

12

13

umask

The umask is a system variable that encodes amask for file permissions to be used when a file iscreated. You can change the variable by executingthe umask command to supply a new value. Thevalue is a three-digit octal value. Each digit is theresult of ORing values from 1, 2, or 4; themeanings are shown in the following table. Theseparate digits refer to “user,” “group,” and“other” permissions, respectively.

The umask is a system variable that encodes amask for file permissions to be used when a file iscreated. You can change the variable by executingthe umask command to supply a new value. Thevalue is a three-digit octal value. Each digit is theresult of ORing values from 1, 2, or 4; themeanings are shown in the following table. Theseparate digits refer to “user,” “group,” and“other” permissions, respectively.

14

15

For example, to block “group” write and execute,and “other” write, the umask would be - 032

16

close

You use close to terminate the associationbetween a file descriptor, fildes, and its file. Thefile descriptor becomes available for reuse. Itreturns 0 if successful and –1 on error.

#include <unistd.h> int close(int fildes);

You use close to terminate the associationbetween a file descriptor, fildes, and its file. Thefile descriptor becomes available for reuse. Itreturns 0 if successful and –1 on error.

#include <unistd.h> int close(int fildes);

17

copy_system.c#include <unistd.h>#include <sys/stat.h>#include <fcntl.h>#include <stdlib.h>int main(){

char c;int in, out;in = open(“file.in”, O_RDONLY);out = open(“file.out”, O_WRONLY|O_CREAT,

S_IRUSR|S_IWUSR);while(read(in,&c,1) == 1)write(out,&c,1);exit(0);

}

#include <unistd.h>#include <sys/stat.h>#include <fcntl.h>#include <stdlib.h>int main(){

char c;int in, out;in = open(“file.in”, O_RDONLY);out = open(“file.out”, O_WRONLY|O_CREAT,

S_IRUSR|S_IWUSR);while(read(in,&c,1) == 1)write(out,&c,1);exit(0);

}18

Other System Calls for Managing Files

lseek fstat, stat, and lstat dup and dup2

19

The Standard I/O Library❑ fopen, fclose❑ fread, fwrite❑ fflush❑ fseek❑ fgetc, getc, getchar❑ fputc, putc, putchar❑ fgets, gets❑ printf, fprintf, and sprintf❑ scanf, fscanf, and sscanf

❑ fopen, fclose❑ fread, fwrite❑ fflush❑ fseek❑ fgetc, getc, getchar❑ fputc, putc, putchar❑ fgets, gets❑ printf, fprintf, and sprintf❑ scanf, fscanf, and sscanf

20

fopen

#include <stdio.h> FILE *fopen(const char *filename, const char

*mode);

21

fread, fwrite

#include <stdio.h> size_t fread(void *ptr, size_t size, size_t nitems,

FILE *stream);

#include <stdio.h> size_t fread(void *ptr, size_t size, size_t nitems,

FILE *stream);

#include <stdio.h> size_t fread(void *ptr, size_t size, size_t nitems,

FILE *stream);

#include <stdio.h> size_t fread(void *ptr, size_t size, size_t nitems,

FILE *stream);

22

fwrite, fclose, fflush

#include <stdio.h> size_t fwrite (const void *ptr, size_t size, size_t

nitems, FILE *stream);

#include <stdio.h> int fclose(FILE *stream);

#include <stdio.h> int fflush(FILE *stream);

#include <stdio.h> size_t fwrite (const void *ptr, size_t size, size_t

nitems, FILE *stream);

#include <stdio.h> int fclose(FILE *stream);

#include <stdio.h> int fflush(FILE *stream);

23

fgetc, getc, and getchar

#include <stdio.h> int fgetc(FILE *stream); int getc(FILE *stream); int getchar();

#include <stdio.h> int fgetc(FILE *stream); int getc(FILE *stream); int getchar();

24

fputc, putc, and putchar

#include <stdio.h> int fputc(int c, FILE *stream); int putc(int c, FILE *stream); int putchar(int c);

#include <stdio.h> int fputc(int c, FILE *stream); int putc(int c, FILE *stream); int putchar(int c);

25

fgets and gets

#include <stdio.h> char *fgets(char *s, int n, FILE *stream); char *gets(char *s);

26

Formatted Input and Output

#include <stdio.h> int printf(const char *format, ...); int sprintf(char *s, const char *format, ...); int fprintf(FILE *stream, const char *format, ...);

int scanf(const char *format, ...); int fscanf(FILE *stream, const char *format, ...); int sscanf(const char *s, const char *format, ...);

#include <stdio.h> int printf(const char *format, ...); int sprintf(char *s, const char *format, ...); int fprintf(FILE *stream, const char *format, ...);

int scanf(const char *format, ...); int fscanf(FILE *stream, const char *format, ...); int sscanf(const char *s, const char *format, ...);

27

Stream Errors

#include <errno.h> extern int errno;

#include <stdio.h> int ferror(FILE *stream); int feof(FILE *stream); void clearerr(FILE *stream);

#include <errno.h> extern int errno;

#include <stdio.h> int ferror(FILE *stream); int feof(FILE *stream); void clearerr(FILE *stream);

28

File and Directory Maintenance

chmod#include <sys/stat.h>int chmod(const char *path, mode_t mode);

chown#include <sys/types.h>#include <unistd.h>int chown(const char *path, uid_t owner, gid_t group);

chmod#include <sys/stat.h>int chmod(const char *path, mode_t mode);

chown#include <sys/types.h>#include <unistd.h>int chown(const char *path, uid_t owner, gid_t group);

29

int unlink(const char *path); int link(const char *path1, const char *path2); int symlink(const char *path1, const char *path2); int mkdir(const char *path, mode_t mode); int rmdir(const char *path); int chdir(const char *path); char *getcwd(char *buf, size_t size);

int unlink(const char *path); int link(const char *path1, const char *path2); int symlink(const char *path1, const char *path2); int mkdir(const char *path, mode_t mode); int rmdir(const char *path); int chdir(const char *path); char *getcwd(char *buf, size_t size);

30

The /proc File System

cat /proc/cpuinfo cat /proc/meminfo cat /proc/version cat /proc/net/sockstat cat /proc/sys/fs/file-max

cat /proc/cpuinfo cat /proc/meminfo cat /proc/version cat /proc/net/sockstat cat /proc/sys/fs/file-max

31

Programming KDE Using Qt

Contents

❑ An introduction to Qt❑ Installing Qt❑ Getting started❑ Signal/slot mechanism❑ Qt widgets❑ Dialogs❑Menus and toolbars with KDE❑ Building your CD database application with KDE/Qt

❑ An introduction to Qt❑ Installing Qt❑ Getting started❑ Signal/slot mechanism❑ Qt widgets❑ Dialogs❑Menus and toolbars with KDE❑ Building your CD database application with KDE/Qt

2

Introducing KDE and Qt

KDE (K Desktop Environment) is an open sourcedesktop environment based on the Qt GUI library.A host of applications and utilities are part ofKDE, including a complete office suite, a Webbrowser, and even a fully featured IDE forprogramming KDE/Qt applications.

KDE (K Desktop Environment) is an open sourcedesktop environment based on the Qt GUI library.A host of applications and utilities are part ofKDE, including a complete office suite, a Webbrowser, and even a fully featured IDE forprogramming KDE/Qt applications.

3

Qt Qt is a mature, cross-platform GUI toolkit written in C++.

Qt is the brainchild of Trolltech, a Norwegian company thatdevelops, markets, and supports Qt and Qt-related softwarefor the commercial market. Trolltech loudly touts the cross-platform capabilities of Qt, which is undeniably impressive;Qt has native support on Linux and UNIX derivatives,Windows, Mac OS X, and even embedded platforms, whichgives Qt a great competitive advantage over its rivals. Aspecialized version of Qt runs on cell phones. Anotherversion runs on the Sharp Zaurus PDA and similar platform.Qt Jambi provides a Java version of the toolkit. Qt OpenSource Edition is licensed under the GPL.

Qt is a mature, cross-platform GUI toolkit written in C++.Qt is the brainchild of Trolltech, a Norwegian company thatdevelops, markets, and supports Qt and Qt-related softwarefor the commercial market. Trolltech loudly touts the cross-platform capabilities of Qt, which is undeniably impressive;Qt has native support on Linux and UNIX derivatives,Windows, Mac OS X, and even embedded platforms, whichgives Qt a great competitive advantage over its rivals. Aspecialized version of Qt runs on cell phones. Anotherversion runs on the Sharp Zaurus PDA and similar platform.Qt Jambi provides a Java version of the toolkit. Qt OpenSource Edition is licensed under the GPL.

4

QMainWindow

//file qt1.cpp

5

To compile, you’ll need to include the Qt includeand lib directories:

$ g++ -o qt1 qt1.cpp –I$QTDIR/include –L$QTDIR/lib –lqui

$ ./qt1

To compile, you’ll need to include the Qt includeand lib directories:

$ g++ -o qt1 qt1.cpp –I$QTDIR/include –L$QTDIR/lib –lqui

$ ./qt1

6

Signals and Slots

Signals and signal handling are the primarymechanisms a GUI application uses to respond touser input and are central features of all GUIlibraries. Qt’s signal-handling mechanism consistsof signals and slots, which are Qt’s names forsignals and callback functions in GTK+ or Javaevents and event handlers.

Signals and signal handling are the primarymechanisms a GUI application uses to respond touser input and are central features of all GUIlibraries. Qt’s signal-handling mechanism consistsof signals and slots, which are Qt’s names forsignals and callback functions in GTK+ or Javaevents and event handlers.

7

Qt

Here’s a reminder of how event-driven programmingworks: A GUI consists of menus, toolbars, buttons, entryboxes, and many other GUI elements that are collectivelyknown as widgets. When the user inter-acts with a widget,for example activating a menu item or entering some text inan entry box, the widget will emit a named signal such asclicked, text_changed, or key_pressed. You’ll usually wantto do something in response to the user’s action, such assave a document or quit the application, and you do this byconnecting a signal to a callback function or, in Qt parlance,a slot.

Here’s a reminder of how event-driven programmingworks: A GUI consists of menus, toolbars, buttons, entryboxes, and many other GUI elements that are collectivelyknown as widgets. When the user inter-acts with a widget,for example activating a menu item or entering some text inan entry box, the widget will emit a named signal such asclicked, text_changed, or key_pressed. You’ll usually wantto do something in response to the user’s action, such assave a document or quit the application, and you do this byconnecting a signal to a callback function or, in Qt parlance,a slot.

8

A typical class definition MyWindow.h for yourGUI will look something like this:

emit aSignal();

9

emit aSignal();

Qt …

To use slots, you must connect them to a signal.You do this with the appropriately named staticconnect method in the QObject class:

bool QObject::connect (const QObject *sender, const char * signal, const QObject *receiver, const char * member)

To use slots, you must connect them to a signal.You do this with the appropriately named staticconnect method in the QObject class:

bool QObject::connect (const QObject *sender, const char * signal, const QObject *receiver, const char * member)

10

Qt …

In the MyWindow example, if you wanted toconnect the clicked signal of a QPushButtonwidget to your doSomething slot, you’d writeconnect (button, SIGNAL(clicked()), this,SLOT(doSomething()));

void MyWindow::doSomething(){// Slot code}

In the MyWindow example, if you wanted toconnect the clicked signal of a QPushButtonwidget to your doSomething slot, you’d writeconnect (button, SIGNAL(clicked()), this,SLOT(doSomething()));

void MyWindow::doSomething(){// Slot code}

11

Exam. Extend QMainWindow and add a button,and connect the button’s clicked signal to a slot.

12

Exam. (cont.)

13

Qt (cont.)

14

Qt. (cont.)

15

Before you can compile this example, you need to run thepreprocessor on the header file. This preprocessorprogram is called the Meta Object Compiler (moc) andshould be present in the Qt package. Run moc onButtonWindow.h, saving the output asButtonWindow.moc:

$ moc ButtonWindow.h –o ButtonWindow.moc Now you can compile as usual, linking in the moc output: $ g++ -o button ButtonWindow.cpp –

I$QTDIR/include –L$QTDIR/lib –lqui

16

Before you can compile this example, you need to run thepreprocessor on the header file. This preprocessorprogram is called the Meta Object Compiler (moc) andshould be present in the Qt package. Run moc onButtonWindow.h, saving the output asButtonWindow.moc:

$ moc ButtonWindow.h –o ButtonWindow.moc Now you can compile as usual, linking in the moc output: $ g++ -o button ButtonWindow.cpp –

I$QTDIR/include –L$QTDIR/lib –lqui

QVBoxLayout(…has an identical API)

QVBoxLayout::QVBoxLayout (QWidget *parent, int margin,int spacing, const char *name)

QVBoxLayout::QVBoxLayout (QLayout *parentLayout, intspacing, const char * name)

QVBoxLayout::QVBoxLayout (int spacing, const char *name) Once you’ve created your QLayout, you add child widgets or

layouts using a couple of methods: QBoxLayout::addWidget (QWidget *widget, int stretch = 0, int

alignment = 0 ) QBoxLayout::addLayout (QLayout *layout, int stretch = 0)

QVBoxLayout::QVBoxLayout (QWidget *parent, int margin,int spacing, const char *name)

QVBoxLayout::QVBoxLayout (QLayout *parentLayout, intspacing, const char * name)

QVBoxLayout::QVBoxLayout (int spacing, const char *name) Once you’ve created your QLayout, you add child widgets or

layouts using a couple of methods: QBoxLayout::addWidget (QWidget *widget, int stretch = 0, int

alignment = 0 ) QBoxLayout::addLayout (QLayout *layout, int stretch = 0)

17

Example: Using QBoxLayout Classes

1. First, enter the header file, LayoutWindow.h:#include <qmainwindow.h>class LayoutWindow : public QMainWindow{Q_OBJECTpublic:LayoutWindow(QWidget *parent = 0, const char *name = 0);virtual ~LayoutWindow();};

1. First, enter the header file, LayoutWindow.h:#include <qmainwindow.h>class LayoutWindow : public QMainWindow{Q_OBJECTpublic:LayoutWindow(QWidget *parent = 0, const char *name = 0);virtual ~LayoutWindow();};

18

2. Now enter the implementation,LayoutWindow.cpp:#include <qapplication.h>#include <qlabel.h>#include <qlayout.h>#include “LayoutWindow.moc”LayoutWindow::LayoutWindow(QWidget *parent,

const char *name) : QMainWindow(parent, name){this->setCaption(“Layouts”);

#include <qapplication.h>#include <qlabel.h>#include <qlayout.h>#include “LayoutWindow.moc”LayoutWindow::LayoutWindow(QWidget *parent,

const char *name) : QMainWindow(parent, name){this->setCaption(“Layouts”);

19

3. You need to create a dummy QWidget to hold your QHBoxLayoutbecause you cannot add a QLayout directly to a QMainWindow:

QWidget *widget = new QWidget(this);setCentralWidget(widget);QHBoxLayout *horizontal = new QHBoxLayout(widget, 5, 10, “horizontal”);QVBoxLayout *vertical = new QVBoxLayout();QLabel* label1 = new QLabel(“Top”, widget, “textLabel1” );QLabel* label2 = new QLabel(“Bottom”, widget, “textLabel2”);QLabel* label3 = new QLabel(“Right”, widget, “textLabel3”);vertical->addWidget(label1);vertical->addWidget(label2);horizontal->addLayout(vertical);horizontal->addWidget(label3);resize( 150, 100 );}

QWidget *widget = new QWidget(this);setCentralWidget(widget);QHBoxLayout *horizontal = new QHBoxLayout(widget, 5, 10, “horizontal”);QVBoxLayout *vertical = new QVBoxLayout();QLabel* label1 = new QLabel(“Top”, widget, “textLabel1” );QLabel* label2 = new QLabel(“Bottom”, widget, “textLabel2”);QLabel* label3 = new QLabel(“Right”, widget, “textLabel3”);vertical->addWidget(label1);vertical->addWidget(label2);horizontal->addLayout(vertical);horizontal->addWidget(label3);resize( 150, 100 );}

20

Cont.

LayoutWindow::~LayoutWindow(){}int main(int argc, char **argv){

QApplication app(argc,argv);LayoutWindow *window = new LayoutWindow();app.setMainWidget(window);window->show();return app.exec();

}

LayoutWindow::~LayoutWindow(){}int main(int argc, char **argv){

QApplication app(argc,argv);LayoutWindow *window = new LayoutWindow();app.setMainWidget(window);window->show();return app.exec();

}21

Run …

$ moc LayoutWindow.h –o LayoutWindow.moc $ g++ -o layout LayoutWindow.cpp –

I$QTDIR/include –L$QTDIR/lib –lqui

22

QLineEdit

QLineEdit is Qt’s single-line text entry widget. Use itfor inputting brief amounts of text, such as a user’sfirst name. With a QLineEdit widget, you can limittext input using an input mask to fit a template or, forthe ultimate control, you can apply a validatorfunction, for example, to ensure the user enters aproper date, phone number, or other similar value.QLineEdit has editing features, enabling you to selectparts of the text, cut and paste, undo, redo, and thelike from both a user’s perspective and using the API.

QLineEdit is Qt’s single-line text entry widget. Use itfor inputting brief amounts of text, such as a user’sfirst name. With a QLineEdit widget, you can limittext input using an input mask to fit a template or, forthe ultimate control, you can apply a validatorfunction, for example, to ensure the user enters aproper date, phone number, or other similar value.QLineEdit has editing features, enabling you to selectparts of the text, cut and paste, undo, redo, and thelike from both a user’s perspective and using the API.

23

The constructors and most useful methods are

#include <qlineedit.h> QLineEdit::QlineEdit (QWidget *parent, const char* name = 0 ) QLineEdit::QLineEdit (const QString &contents, QWidget

*parent, const char *name = 0 ) QLineEdit::QLineEdit (const QString &contents, const QString

&inputMask, QWidget *parent, const char *name = 0 ) void setInputMask (const QString &inputMask) void insert (const QString &newText ) bool isModified (void)

#include <qlineedit.h> QLineEdit::QlineEdit (QWidget *parent, const char* name = 0 ) QLineEdit::QLineEdit (const QString &contents, QWidget

*parent, const char *name = 0 ) QLineEdit::QLineEdit (const QString &contents, const QString

&inputMask, QWidget *parent, const char *name = 0 ) void setInputMask (const QString &inputMask) void insert (const QString &newText ) bool isModified (void)

24

void setMaxLength (int length) void setReadOnly (bool read) void setText (const QString &text) QString text (void) void setEchoMode(EchoMode mode)

void setMaxLength (int length) void setReadOnly (bool read) void setText (const QString &text) QString text (void) void setEchoMode(EchoMode mode)

25

EchoMode

It can take one of three values:❑ QLineEdit::Normal: Display inputted characters

(default)❑ QLineEdit::Password: Display asterisks in place

of characters❑ QLineEdit::NoEcho: Display nothing Set the mode using the setEchoMode: lineEdit->setEchoMode(QLineEdit::Password);

It can take one of three values:❑ QLineEdit::Normal: Display inputted characters

(default)❑ QLineEdit::Password: Display asterisks in place

of characters❑ QLineEdit::NoEcho: Display nothing Set the mode using the setEchoMode: lineEdit->setEchoMode(QLineEdit::Password);

26

inputMask is a string made up of characters, each of whichcorresponds to a rule that accepts a certain range of characters

27

Example. QLineEdit

28

29

30

Step3. Cont.

31

Qt Buttons

QButton: The Button Base Class #include <qbutton.h> virtual void QButton::setText ( const QString & ) virtual void QButton::setPixmap ( const QPixmap & ) bool QButton::isToggleButton () const virtual void QButton::setDown ( bool ) bool QButton::isDown () const bool QButton::isOn () const enum QButton::ToggleState { Off, NoChange, On } ToggleState QButton::state () const

QButton: The Button Base Class #include <qbutton.h> virtual void QButton::setText ( const QString & ) virtual void QButton::setPixmap ( const QPixmap & ) bool QButton::isToggleButton () const virtual void QButton::setDown ( bool ) bool QButton::isDown () const bool QButton::isOn () const enum QButton::ToggleState { Off, NoChange, On } ToggleState QButton::state () const

32

QPushButton

QPushButton is the standard generic button that containstext such as “OK” or “Cancel” and/or a pixmap icon. Likeall QButtons, it emits the clicked signal when it’sactivated, and is usually used to connect a slot andperform some action.

#include <qpushbutton.h> QPushButton (QWidget *parent, const char *name = 0) QPushButton (const QString &text, QWidget *parent, const

char *name = 0) QPushButton (const QIconSet &icon, const QString &text, QWidget *parent, const char * name = 0 ) void QPushButton::setToggleButton (bool);

QPushButton is the standard generic button that containstext such as “OK” or “Cancel” and/or a pixmap icon. Likeall QButtons, it emits the clicked signal when it’sactivated, and is usually used to connect a slot andperform some action.

#include <qpushbutton.h> QPushButton (QWidget *parent, const char *name = 0) QPushButton (const QString &text, QWidget *parent, const

char *name = 0) QPushButton (const QIconSet &icon, const QString &text, QWidget *parent, const char * name = 0 ) void QPushButton::setToggleButton (bool);

33

QCheckBox

QCheckBox is a button that has state; that is, it can be turnedon or off. The appearance of QCheckBox depends on thecurrent windowing style (Motif, Windows, and so on) but isusually drawn as a ticked box with text to the right.

#include <qcheckbox.h> QCheckBox (QWidget *parent, const char *name = 0 ) QCheckBox (const QString &text, QWidget *parent,

const char *name = 0 ) bool QCheckBox::isChecked () void QCheckBox::setTristate ( bool y = TRUE ) bool QCheckBox::isTristate ()

QCheckBox is a button that has state; that is, it can be turnedon or off. The appearance of QCheckBox depends on thecurrent windowing style (Motif, Windows, and so on) but isusually drawn as a ticked box with text to the right.

#include <qcheckbox.h> QCheckBox (QWidget *parent, const char *name = 0 ) QCheckBox (const QString &text, QWidget *parent,

const char *name = 0 ) bool QCheckBox::isChecked () void QCheckBox::setTristate ( bool y = TRUE ) bool QCheckBox::isTristate ()

34

QRadioButton Radio buttons are toggle buttons used to represent exclusive choices

when you can select only one option out of a group of optionspresented (think back to those old car radios, where only one stationbutton could be pressed in at a time)

#include <qbuttongroup.h> QButtonGroup (QWidget *parent = 0, const char * name = 0 ) QButtonGroup (const QString & title, QWidget * parent = 0,

const char * name = 0 ) int insert (QButton *button, int id = -1) void remove (QButton *button) int id (QButton *button) const int count () const int selectedId () const

Radio buttons are toggle buttons used to represent exclusive choiceswhen you can select only one option out of a group of optionspresented (think back to those old car radios, where only one stationbutton could be pressed in at a time)

#include <qbuttongroup.h> QButtonGroup (QWidget *parent = 0, const char * name = 0 ) QButtonGroup (const QString & title, QWidget * parent = 0,

const char * name = 0 ) int insert (QButton *button, int id = -1) void remove (QButton *button) int id (QButton *button) const int count () const int selectedId () const

35

QRadioButton

The QRadioButton constructors and one uniquemethod shouldn’t be too surprising:

#include <qradiobutton.h> QRadioButton (QWidget *parent, const char *name = 0 ) QRadioButton (const QString &text, QWidget *parent,

const char *name = 0 ) bool QRadioButton::isChecked ()

The QRadioButton constructors and one uniquemethod shouldn’t be too surprising:

#include <qradiobutton.h> QRadioButton (QWidget *parent, const char *name = 0 ) QRadioButton (const QString &text, QWidget *parent,

const char *name = 0 ) bool QRadioButton::isChecked ()

36

Example. QButtons

1. Enter Buttons.h:#include <qmainwindow.h>#include <qcheckbox.h>#include <qbutton.h>#include <qradiobutton.h>class Buttons : public QMainWindow{Q_OBJECTpublic:Buttons(QWidget *parent = 0, const char *name = 0);

1. Enter Buttons.h:#include <qmainwindow.h>#include <qcheckbox.h>#include <qbutton.h>#include <qradiobutton.h>class Buttons : public QMainWindow{Q_OBJECTpublic:Buttons(QWidget *parent = 0, const char *name = 0);

37

2. You’ll query the state of your buttons later in the slotfunction, so declare the button pointers as private in the classdefinition, as well as a helper function PrintActive:

private:void PrintActive(QButton *button);QCheckBox *checkbox;QRadioButton *radiobutton1, *radiobutton2;private slots:void Clicked();};

2. You’ll query the state of your buttons later in the slotfunction, so declare the button pointers as private in the classdefinition, as well as a helper function PrintActive:

private:void PrintActive(QButton *button);QCheckBox *checkbox;QRadioButton *radiobutton1, *radiobutton2;private slots:void Clicked();};

38

3. Here’s Buttons.cpp:#include “Buttons.moc”#include <qbuttongroup.h>#include <qpushbutton.h>#include <qapplication.h>#include <qlabel.h>#include <qlayout.h>#include <iostream>Buttons::Buttons(QWidget *parent, const char *name) :

QMainWindow(parent, name){QWidget *widget = new QWidget(this);setCentralWidget(widget);QVBoxLayout *vbox = new QVBoxLayout(widget,5, 10,”vbox”);checkbox = new QCheckBox(“CheckButton”, widget, “check”);vbox->addWidget(checkbox);

#include “Buttons.moc”#include <qbuttongroup.h>#include <qpushbutton.h>#include <qapplication.h>#include <qlabel.h>#include <qlayout.h>#include <iostream>Buttons::Buttons(QWidget *parent, const char *name) :

QMainWindow(parent, name){QWidget *widget = new QWidget(this);setCentralWidget(widget);QVBoxLayout *vbox = new QVBoxLayout(widget,5, 10,”vbox”);checkbox = new QCheckBox(“CheckButton”, widget, “check”);vbox->addWidget(checkbox); 39

4. Here you create a QButtonGroup foryour two radio buttons:QButtonGroup *buttongroup = new QButtonGroup(0);radiobutton1 = new QRadioButton(“RadioButton1”, widget, “radio1”);buttongroup->insert(radiobutton1);vbox->addWidget(radiobutton1);radiobutton2 = new QRadioButton(“RadioButton2”, widget, “radio2”);buttongroup->insert(radiobutton2);vbox->addWidget(radiobutton2);QPushButton *button = new QPushButton (“Ok”, widget, “button”);vbox->addWidget(button);resize( 350, 200 );connect (button, SIGNAL(clicked()), this, SLOT(Clicked()));}

QButtonGroup *buttongroup = new QButtonGroup(0);radiobutton1 = new QRadioButton(“RadioButton1”, widget, “radio1”);buttongroup->insert(radiobutton1);vbox->addWidget(radiobutton1);radiobutton2 = new QRadioButton(“RadioButton2”, widget, “radio2”);buttongroup->insert(radiobutton2);vbox->addWidget(radiobutton2);QPushButton *button = new QPushButton (“Ok”, widget, “button”);vbox->addWidget(button);resize( 350, 200 );connect (button, SIGNAL(clicked()), this, SLOT(Clicked()));}

40

5. Next is a convenience method for printing thestate of the given QButton:

void Buttons::PrintActive(QButton *button){if (button->isOn())std::cout << button->name() << “ is checked\n”;elsestd::cout << button->name() << “ is not checked\n”;}void Buttons::Clicked(void){PrintActive(checkbox);PrintActive(radiobutton1);PrintActive(radiobutton2);std::cout << “\n”;}

void Buttons::PrintActive(QButton *button){if (button->isOn())std::cout << button->name() << “ is checked\n”;elsestd::cout << button->name() << “ is not checked\n”;}void Buttons::Clicked(void){PrintActive(checkbox);PrintActive(radiobutton1);PrintActive(radiobutton2);std::cout << “\n”;} 41

QButton

int main(int argc, char **argv){QApplication app(argc,argv);Buttons *window = new Buttons();app.setMainWidget(window);window->show();return app.exec();}

int main(int argc, char **argv){QApplication app(argc,argv);Buttons *window = new Buttons();app.setMainWidget(window);window->show();return app.exec();}

42

QComboBox

1. Enter the following and name the file ComboBox.h:#include <qmainwindow.h>#include <qcombobox.h>class ComboBox : public QMainWindow{Q_OBJECTpublic:ComboBox(QWidget *parent = 0, const char *name = 0);private slots:void Changed(const QString& s);};

1. Enter the following and name the file ComboBox.h:#include <qmainwindow.h>#include <qcombobox.h>class ComboBox : public QMainWindow{Q_OBJECTpublic:ComboBox(QWidget *parent = 0, const char *name = 0);private slots:void Changed(const QString& s);};

43

2. The interface consists of two QComboBox widgets, one editable and theother read-only. You populate both widgets with the same list of items:

#include “ComboBox.moc”#include <qlayout.h>#include <iostream>ComboBox::ComboBox(QWidget *parent, const char

*name) : QMainWindow(parent, name){QWidget *widget = new QWidget(this);setCentralWidget(widget);QVBoxLayout *vbox = new QVBoxLayout(widget, 5,

10,”vbox”);

#include “ComboBox.moc”#include <qlayout.h>#include <iostream>ComboBox::ComboBox(QWidget *parent, const char

*name) : QMainWindow(parent, name){QWidget *widget = new QWidget(this);setCentralWidget(widget);QVBoxLayout *vbox = new QVBoxLayout(widget, 5,

10,”vbox”);44

QComboBox *editablecombo = new QComboBox(TRUE, widget,“editable”);

vbox->addWidget(editablecombo);QComboBox *readonlycombo = new QComboBox(FALSE, widget,

“readonly”);vbox->addWidget(readonlycombo);static const char* items[] = { “Macbeth”, “Twelfth Night”, “Othello”, 0

};editablecombo->insertStrList (items);readonlycombo->insertStrList (items);connect (editablecombo, SIGNAL(textChanged(const QString&)),this, SLOT(Changed(const QString&)));resize( 350, 200 );}

QComboBox *editablecombo = new QComboBox(TRUE, widget,“editable”);

vbox->addWidget(editablecombo);QComboBox *readonlycombo = new QComboBox(FALSE, widget,

“readonly”);vbox->addWidget(readonlycombo);static const char* items[] = { “Macbeth”, “Twelfth Night”, “Othello”, 0

};editablecombo->insertStrList (items);readonlycombo->insertStrList (items);connect (editablecombo, SIGNAL(textChanged(const QString&)),this, SLOT(Changed(const QString&)));resize( 350, 200 );}

45

3. This is the slot function. Note the QStringparameter s that’s passed by the signal:

void ComboBox::Changed(const QString& s){std::cout << s << “\n”;}int main(int argc, char **argv){QApplication app(argc,argv);ComboBox *window = new ComboBox();app.setMainWidget(window);window->show();return app.exec();}

void ComboBox::Changed(const QString& s){std::cout << s << “\n”;}int main(int argc, char **argv){QApplication app(argc,argv);ComboBox *window = new ComboBox();app.setMainWidget(window);window->show();return app.exec();}

46

QListView

Lists and trees in Qt are provided by the QListViewwidget. QListView displays both plain lists andhierarchical data divided into rows and columns. It’sperfect for displaying things like directory structures,because the child elements can be expanded andcontracted by clicking the plus and minus boxes, justlike a file viewer. With QListView, you can selectrows or individual cells; then cut and paste the data,sort by column, and you’ll have QCheckBox widgetsrendered in cells.

Lists and trees in Qt are provided by the QListViewwidget. QListView displays both plain lists andhierarchical data divided into rows and columns. It’sperfect for displaying things like directory structures,because the child elements can be expanded andcontracted by clicking the plus and minus boxes, justlike a file viewer. With QListView, you can selectrows or individual cells; then cut and paste the data,sort by column, and you’ll have QCheckBox widgetsrendered in cells.

47

Dialogs

Dialogs are useful whenever you want the user to inputspecific information for a particular task, or impart smallamounts of information to the user, such as a warning orerror message. It’s preferable to subclass QDialog forthese tasks because you get convenient methods forrunning the dialog and purpose-designed signals and slotsto handle the user response.

Modal dialog box Nonmodal dialog box Semimodal dialog box

Dialogs are useful whenever you want the user to inputspecific information for a particular task, or impart smallamounts of information to the user, such as a warning orerror message. It’s preferable to subclass QDialog forthese tasks because you get convenient methods forrunning the dialog and purpose-designed signals and slotsto handle the user response.

Modal dialog box Nonmodal dialog box Semimodal dialog box

48

QDialog

QDialog is the base dialog class in Qt thatprovides exec and show methods for handlingmodal and nonmodal dialogs, has an integralQLayout you can use, and has several signals andslots useful for responding to button presses.

QDialog is the base dialog class in Qt thatprovides exec and show methods for handlingmodal and nonmodal dialogs, has an integralQLayout you can use, and has several signals andslots useful for responding to button presses.

49

QMessageBox

A QMessageBox is a modal dialog that displays asimple message with an icon and buttons. Theicon depends on the severity of the message,which can be regular information or warnings andother critical information.

#include <qmessagebox.h>

A QMessageBox is a modal dialog that displays asimple message with an icon and buttons. Theicon depends on the severity of the message,which can be regular information or warnings andother critical information.

#include <qmessagebox.h>

50

QInputDialog

QInputDialog is useful for inputting single valuesfrom the user, which can either be text, an optionfrom a drop-down list, an integer, or a floating-point value. The QInputDialog class has staticmethods like QMessageBox that are a bit of ahandful because they have many parameters, butfortunately most have default values.

#include <qinputdialog.h>

QInputDialog is useful for inputting single valuesfrom the user, which can either be text, an optionfrom a drop-down list, an integer, or a floating-point value. The QInputDialog class has staticmethods like QMessageBox that are a bit of ahandful because they have many parameters, butfortunately most have default values.

#include <qinputdialog.h>

51