0% found this document useful (0 votes)
289 views

BASH Programming

This document provides an introduction to BASH programming, covering topics such as very simple scripts, redirection, pipes, variables, conditionals, loops, functions, debugging and more. It is intended to help readers start writing basic and intermediate shell scripts, and includes many examples and explanations. The document does not claim to be an advanced reference and is meant to teach programming concepts through practical examples. Feedback is welcomed to improve the content, especially in the form of code patches.

Uploaded by

Agnathavasi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
289 views

BASH Programming

This document provides an introduction to BASH programming, covering topics such as very simple scripts, redirection, pipes, variables, conditionals, loops, functions, debugging and more. It is intended to help readers start writing basic and intermediate shell scripts, and includes many examples and explanations. The document does not claim to be an advanced reference and is meant to teach programming concepts through practical examples. Feedback is welcomed to improve the content, especially in the form of code patches.

Uploaded by

Agnathavasi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 150

BASH Programming - Introduction HOW-

TO
by Mike G mikkey at dynamo.com.ar

Thu Jul 27 09:36:18 ART 2000

This article intends to help you to start programming basic-intermediate shell scripts.
It does not intend to be an advanced document (see the title). I am NOT an expert nor
guru shell programmer. I decided to write this because I'll learn a lot and it might be
useful to other people. Any feedback will be apreciated, specially in the patch form :)

1. Introduction
 1.1 Getting the latest version
 1.2 Requisites
 1.3 Uses of this document

2. Very simple Scripts


 2.1 Traditional hello world script
 2.2 A very simple backup script

3. All about redirection


 3.1 Theory and quick reference
 3.2 Sample: stdout 2 file
 3.3 Sample: stderr 2 file
 3.4 Sample: stdout 2 stderr
 3.5 Sample: stderr 2 stdout
 3.6 Sample: stderr and stdout 2 file

4. Pipes
 4.1 What they are and why you'll want to use them
 4.2 Sample: simple pipe with sed
 4.3 Sample: an alternative to ls -l *.txt
5. Variables
 5.1 Sample: Hello World! using variables
 5.2 Sample: A very simple backup script (little bit better)
 5.3 Local variables

6. Conditionals
 6.1 Dry Theory
 6.2 Sample: Basic conditional example if .. then
 6.3 Sample: Basic conditional example if .. then ... else
 6.4 Sample: Conditionals with variables

7. Loops for, while and until


 7.1 For sample
 7.2 C-like for
 7.3 While sample
 7.4 Until sample

8. Functions
 8.1 Functions sample
 8.2 Functions with parameters sample

9. User interfaces
 9.1 Using select to make simple menus
 9.2 Using the command line

10. Misc
 10.1 Reading user input with read
 10.2 Arithmetic evaluation
 10.3 Finding bash
 10.4 Getting the return value of a program
 10.5 Capturing a commands output
 10.6 Multiple source files

11. Tables
 11.1 String comparison operators
 11.2 String comparison examples
 11.3 Arithmetic operators
 11.4 Arithmetic relational operators
 11.5 Useful commands

12. More Scripts


 12.1 Applying a command to all files in a directory.
 12.2 Sample: A very simple backup script (little bit better)
 12.3 File re-namer
 12.4 File renamer (simple)

13. When something goes wrong (debugging)


 13.1 Ways Calling BASH

14. About the document


 14.1 (no) warranty
 14.2 Translations
 14.3 Thanks to
 14.4 History
 14.5 More resources

1. Introduction
1.1 Getting the latest version
http://www.linuxdoc.org/HOWTO/Bash-Prog-Intro-HOWTO.html

1.2 Requisites
Familiarity with GNU/Linux command lines, and familiarity with basic programming
concepts is helpful. While this is not a programming introduction, it explains (or at
least tries) many basic concepts.

1.3 Uses of this document


This document tries to be useful in the following situations
 You have an idea about programming and you want to start coding some shell
scripts.
 You have a vague idea about shell programming and want some sort of
reference.
 You want to see some shell scripts and some comments to start writing your
own
 You are migrating from DOS/Windows (or already did) and want to make
"batch" processes.
 You are a complete nerd and read every how-to available
 2. Very simple Scripts
 This HOW-TO will try to give you some hints about shell script programming
strongly based on examples.
 In this section you'll find some little scripts which will hopefully help you to
understand some techniques.
 2.1 Traditional hello world script
 #!/bin/bash
 echo Hello World

 This script has only two lines. The first indicates the system which program to
use to run the file.
 The second line is the only action performed by this script, which prints 'Hello
World' on the terminal.
 If you get something like ./hello.sh: Command not found. Probably the first line
'#!/bin/bash' is wrong, issue whereis bash or see 'finding bash' to see how sould
you write this line.
 2.2 A very simple backup script
 #!/bin/bash
 tar -cZf /var/my-backup.tgz /home/me/

 In this script, instead of printing a message on the terminal, we create a tar-ball
of a user's home directory. This is NOT intended to be used, a more useful
backup script is presented later in this document.

3. All about redirection


3.1 Theory and quick reference
There are 3 file descriptors, stdin, stdout and stderr (std=standard).

Basically you can:


1. redirect stdout to a file
2. redirect stderr to a file
3. redirect stdout to a stderr
4. redirect stderr to a stdout
5. redirect stderr and stdout to a file
6. redirect stderr and stdout to stdout
7. redirect stderr and stdout to stderr

1 'represents' stdout and 2 stderr.

A little note for seeing this things: with the less command you can view both stdout
(which will remain on the buffer) and the stderr that will be printed on the screen, but
erased as you try to 'browse' the buffer.

3.2 Sample: stdout 2 file


This will cause the ouput of a program to be written to a file.
ls -l > ls-l.txt

Here, a file called 'ls-l.txt' will be created and it will contain what you would see on
the screen if you type the command 'ls -l' and execute it.

3.3 Sample: stderr 2 file


This will cause the stderr ouput of a program to be written to a file.
grep da * 2> grep-errors.txt

Here, a file called 'grep-errors.txt' will be created and it will contain what you would
see the stderr portion of the output of the 'grep da *' command.

3.4 Sample: stdout 2 stderr


This will cause the stderr ouput of a program to be written to the same filedescriptor
than stdout.
grep da * 1>&2

Here, the stdout portion of the command is sent to stderr, you may notice that in
differen ways.
3.5 Sample: stderr 2 stdout
This will cause the stderr ouput of a program to be written to the same filedescriptor
than stdout.
grep * 2>&1

Here, the stderr portion of the command is sent to stdout, if you pipe to less, you'll see
that lines that normally 'dissapear' (as they are written to stderr) are being kept now
(because they're on stdout).

3.6 Sample: stderr and stdout 2 file


This will place every output of a program to a file. This is suitable sometimes for cron
entries, if you want a command to pass in absolute silence.
rm -f $(find / -name core) &> /dev/null

This (thinking on the cron entry) will delete every file called 'core' in any directory.
Notice that you should be pretty sure of what a command is doing if you are going to
wipe it's output.

4. Pipes
This section explains in a very simple and practical way how to use pipes, nd why you
may want it.

4.1 What they are and why you'll want to use them
Pipes let you use (very simple, I insist) the output of a program as the input of another
one

4.2 Sample: simple pipe with sed


This is very simple way to use pipes.
ls -l | sed -e "s/[aeio]/u/g"

Here, the following happens: first the command ls -l is executed, and it's output,
instead of being printed, is sent (piped) to the sed program, which in turn, prints what
it has to.
4.3 Sample: an alternative to ls -l *.txt
Probably, this is a more difficult way to do ls -l *.txt, but it is here for illustrating
pipes, not for solving such listing dilema.
ls -l | grep "\.txt$"

Here, the output of the program ls -l is sent to the grep program, which, in turn, will
print lines which match the regex "\.txt$".

5. Variables
You can use variables as in any programming languages. There are no data types. A
variable in bash can contain a number, a character, a string of characters.

You have no need to declare a variable, just assigning a value to its reference will
create it.

5.1 Sample: Hello World! using variables


#!/bin/bash
STR="Hello World!"
echo $STR

Line 2 creates a variable called STR and assigns the string "Hello World!" to it. Then
the VALUE of this variable is retrieved by putting the '$' in at the beginning. Please
notice (try it!) that if you don't use the '$' sign, the output of the program will be
different, and probably not what you want it to be.

5.2 Sample: A very simple backup script (little bit better)


#!/bin/bash
OF=/var/my-backup-$(date +%Y%m%d).tgz
tar -cZf $OF /home/me/

This script introduces another thing. First of all, you should be familiarized with the
variable creation and assignation on line 2. Notice the expression '$(date +%Y%m
%d)'. If you run the script you'll notice that it runs the command inside the
parenthesis, capturing its output.
Notice that in this script, the output filename will be different every day, due to the
format switch to the date command(+%Y%m%d). You can change this by specifying
a different format.

Some more examples:

echo ls

echo $(ls)

5.3 Local variables


Local variables can be created by using the keyword local.
#!/bin/bash
HELLO=Hello
function hello {
local HELLO=World
echo $HELLO
}
echo $HELLO
hello
echo $HELLO

This example should be enought to show how to use a local variable.

6. Conditionals
Conditionals let you decide whether to perform an action or not, this decision is taken
by evaluating an expression.

6.1 Dry Theory


Conditionals have many forms. The most basic form
is: if expression then statement where 'statement' is only executed if 'expression'
evaluates to true. '2<1' is an expresion that evaluates to false, while '2>1' evaluates to
true.xs

Conditionals have other forms such as: if expression then statement1 else statement2.
Here 'statement1' is executed if 'expression' is true,otherwise 'statement2' is executed.

Yet another form of conditionals is: if expression1 then statement1 else


if expression2 then statement2 else statement3. In this form there's added only the
"ELSE IF 'expression2' THEN 'statement2'" which makes statement2 being executed
if expression2 evaluates to true. The rest is as you may imagine (see previous forms).

A word about syntax:

The base for the 'if' constructions in bash is this:

if [expression];

then

code if 'expression' is true.

fi

6.2 Sample: Basic conditional example if .. then


#!/bin/bash
if [ "foo" = "foo" ]; then
echo expression evaluated as true
fi

The code to be executed if the expression within braces is true can be found after the
'then' word and before 'fi' which indicates the end of the conditionally executed code.

6.3 Sample: Basic conditional example if .. then ... else


#!/bin/bash
if [ "foo" = "foo" ]; then
echo expression evaluated as true
else
echo expression evaluated as false
fi

6.4 Sample: Conditionals with variables


#!/bin/bash
T1="foo"
T2="bar"
if [ "$T1" = "$T2" ]; then
echo expression evaluated as true
else
echo expression evaluated as false
fi
7. Loops for, while and until
In this section you'll find for, while and until loops.

The for loop is a little bit different from other programming languages. Basically, it
let's you iterate over a series of 'words' within a string.

The while executes a piece of code if the control expression is true, and only stops
when it is false (or a explicit break is found within the executed code.

The until loop is almost equal to the while loop, except that the code is executed
while the control expression evaluates to false.

If you suspect that while and until are very similar you are right.

7.1 For sample


#!/bin/bash
for i in $( ls ); do
echo item: $i
done

On the second line, we declare i to be the variable that will take the different values
contained in $( ls ).

The third line could be longer if needed, or there could be more lines before the done
(4).

'done' (4) indicates that the code that used the value of $i has finished and $i can take
a new value.

This script has very little sense, but a more useful way to use the for loop would be to
use it to match only certain files on the previous example

7.2 C-like for


fiesh suggested adding this form of looping. It's a for loop more similar to C/perl...
for.
#!/bin/bash
for i in `seq 1 10`;
do
echo $i
done

7.3 While sample


#!/bin/bash
COUNTER=0
while [ $COUNTER -lt 10 ]; do
echo The counter is $COUNTER
let COUNTER=COUNTER+1
done

This script 'emulates' the well known (C, Pascal, perl, etc) 'for' structure

7.4 Until sample


#!/bin/bash
COUNTER=20
until [ $COUNTER -lt 10 ]; do
echo COUNTER $COUNTER
let COUNTER-=1
done

8. Functions
As in almost any programming language, you can use functions to group pieces of
code in a more logical way or practice the divine art of recursion.

Declaring a function is just a matter of writing function my_func { my_code }.

Calling a function is just like calling another program, you just write its name.

8.1 Functions sample


#!/bin/bash
function quit {
exit
}
function hello {
echo Hello!
}
hello
quit
echo foo
Lines 2-4 contain the 'quit' function. Lines 5-7 contain the 'hello' function If you are
not absolutely sure about what this script does, please try it!.

Notice that a functions don't need to be declared in any specific order.

When running the script you'll notice that first: the function 'hello' is called, second
the 'quit' function, and the program never reaches line 10.

8.2 Functions with parameters sample


#!/bin/bash
function quit {
exit
}
function e {
echo $1
}
e Hello
e World
quit
echo foo

This script is almost identically to the previous one. The main difference is the
funcion 'e'. This function, prints the first argument it receives. Arguments, within
funtions, are treated in the same manner as arguments given to the script.

9. User interfaces
9.1 Using select to make simple menus
#!/bin/bash
OPTIONS="Hello Quit"
select opt in $OPTIONS; do
if [ "$opt" = "Quit" ]; then
echo done
exit
elif [ "$opt" = "Hello" ]; then
echo Hello World
else
clear
echo bad option
fi
done
If you run this script you'll see that it is a programmer's dream for text based menus.
You'll probably notice that it's very similar to the 'for' construction, only rather than
looping for each 'word' in $OPTIONS, it prompts the user.

9.2 Using the command line


#!/bin/bash
if [ -z "$1" ]; then
echo usage: $0 directory
exit
fi
SRCD=$1
TGTD="/var/backups/"
OF=home-$(date +%Y%m%d).tgz
tar -cZf $TGTD$OF $SRCD

What this script does should be clear to you. The expression in the first conditional
tests if the program has received an argument ($1) and quits if it didn't, showing the
user a little usage message. The rest of the script should be clear at this point.

10. Misc
10.1 Reading user input with read
In many ocations you may want to prompt the user for some input, and there are
several ways to achive this. This is one of those ways:
#!/bin/bash
echo Please, enter your name
read NAME
echo "Hi $NAME!"

As a variant, you can get multiple values with read, this example may clarify this.
#!/bin/bash
echo Please, enter your firstname and lastname
read FN LN
echo "Hi! $LN, $FN !"

10.2 Arithmetic evaluation


On the command line (or a shell) try this:
echo 1 + 1

If you expected to see '2' you'll be disappointed. What if you want BASH to evaluate
some numbers you have? The solution is this:

echo $((1+1))

This will produce a more 'logical' output. This is to evaluate an arithmetic expression.
You can achieve this also like this:

echo $[1+1]

If you need to use fractions, or more math or you just want it, you can use bc to
evaluate arithmetic expressions.

if i ran "echo $[3/4]" at the command prompt, it would return 0 because bash only
uses integers when answering. If you ran "echo 3/4|bc -l", it would properly return
0.75.

10.3 Finding bash


From a message from mike (see Thanks to)

you always use #!/bin/bash .. you might was to give an example of

how to find where bash is located.

'locate bash' is preferred, but not all machines have locate.

'find ./ -name bash' from the root dir will work, usually.

Suggested locations to check:

ls -l /bin/bash

ls -l /sbin/bash

ls -l /usr/local/bin/bash

ls -l /usr/bin/bash

ls -l /usr/sbin/bash
ls -l /usr/local/sbin/bash

(can't think of any other dirs offhand... i've found it in

most of these places before on different system).

You may try also 'which bash'.

10.4 Getting the return value of a program


In bash, the return value of a program is stored in a special variable called $?.

This illustrates how to capture the return value of a program, I assume that the
directory dada does not exist. (This was also suggested by mike)
#!/bin/bash
cd /dada &> /dev/null
echo rv: $?
cd $(pwd) &> /dev/null
echo rv: $?

10.5 Capturing a commands output


This little scripts show all tables from all databases (assuming you got MySQL
installed). Also, consider changing the 'mysql' command to use a valid username and
password.
#!/bin/bash
DBS=`mysql -uroot -e"show databases"`
for b in $DBS ;
do
mysql -uroot -e"show tables from $b"
done

10.6 Multiple source files


You can use multiple files with the command source.

__TO-DO__

11. Tables
11.1 String comparison operators
(1) s1 = s2

(2) s1 != s2

(3) s1 < s2

(4) s1 > s2

(5) -n s1

(6) -z s1

(1) s1 matches s2

(2) s1 does not match s2

(3) __TO-DO__

(4) __TO-DO__

(5) s1 is not null (contains one or more characters)

(6) s1 is null

11.2 String comparison examples


Comparing two strings.
#!/bin/bash
S1='string'
S2='String'
if [ $S1=$S2 ];
then
echo "S1('$S1') is not equal to S2('$S2')"
fi
if [ $S1=$S1 ];
then
echo "S1('$S1') is equal to S1('$S1')"
fi

I quote here a note from a mail, sent buy Andreas Beck, refering to use if [ $1 = $2 ].

This is not quite a good idea, as if either $S1 or $S2 is empty, you will get a parse
error. x$1=x$2 or "$1"="$2" is better.
11.3 Arithmetic operators
+

% (remainder)

11.4 Arithmetic relational operators


-lt (<)

-gt (>)

-le (<=)

-ge (>=)

-eq (==)

-ne (!=)

C programmer's should simple map the operator to its corresponding parenthesis.

11.5 Useful commands


This section was re-written by Kees (see thank to...)

Some of these command's almost contain complete programming languages. From


those commands only the basics will be explained. For a more detailed description,
have a closer look at the man pages of each command.

sed (stream editor)

Sed is a non-interactive editor. Instead of altering a file by moving the cursor on the
screen, you use a script of editing instructions to sed, plus the name of the file to edit.
You can also describe sed as a filter. Let's have a look at some examples:
$sed 's/to_be_replaced/replaced/g' /tmp/dummy

Sed replaces the string 'to_be_replaced' with the string 'replaced' and reads from the
/tmp/dummy file. The result will be sent to stdout (normally the console) but you can
also add '> capture' to the end of the line above so that sed sends the output to the file
'capture'.
$sed 12, 18d /tmp/dummy

Sed shows all lines except lines 12 to 18. The original file is not altered by this
command.

awk (manipulation of datafiles, text retrieval and processing)

Many implementations of the AWK programming language exist (most known


interpreters are GNU's gawk and 'new awk' mawk.) The principle is simple: AWK
scans for a pattern, and for every matching pattern a action will be performed.

Again, I've created a dummy file containing the following lines:

"test123

test

tteesstt"
$awk '/test/ {print}' /tmp/dummy

test123

test

The pattern AWK looks for is 'test' and the action it performs when it found a line in
the file /tmp/dummy with the string 'test' is 'print'.
$awk '/test/ {i=i+1} END {print i}' /tmp/dummy

When you're searching for many patterns, you should replace the text between the
quotes with '-f file.awk' so you can put all patterns and actions in 'file.awk'.
grep (print lines matching a search pattern)

We've already seen quite a few grep commands in the previous chapters, that display
the lines matching a pattern. But grep can do more.
$grep "look for this" /var/log/messages -c

12

The string "look for this" has been found 12 times in the file /var/log/messages.

[ok, this example was a fake, the /var/log/messages was tweaked :-)]

wc (counts lines, words and bytes)

In the following example, we see that the output is not what we expected. The dummy
file, as used in this example, contains the following text: "bash introduction howto
test file"
$wc --words --lines --bytes /tmp/dummy

2 5 34 /tmp/dummy

Wc doesn't care about the parameter order. Wc always prints them in a standard order,
which is, as you can see: .

sort (sort lines of text files)

This time the dummy file contains the following text:

"b

a"
$sort /tmp/dummy

This is what the output looks like:

a
b

Commands shouldn't be that easy :-) bc (a calculator programming language)

Bc is accepting calculations from command line (input from file. not from redirector
or pipe), but also from a user interface. The following demonstration shows some of
the commands. Note that

I start bc using the -q parameter to avoid a welcome message.


$bc -q

1 == 5

0.05 == 0.05

5 != 5

2^8

256

sqrt(9)

while (i != 9) {

i = i + 1;

print i

123456789
quit

tput (initialize a terminal or query terminfo database)

A little demonstration of tput's capabilities:


$tput cup 10 4

The prompt appears at (y10,x4).


$tput reset

Clears screen and prompt appears at (y1,x1). Note that (y0,x0) is the upper left corner.
$tput cols

80

Shows the number of characters possible in x direction.

It it higly recommended to be familiarized with these programs (at least). There are
tons of little programs that will let you do real magic on the command line.

[some samples are taken from man pages or FAQs]

12. More Scripts


12.1 Applying a command to all files in a directory.
12.2 Sample: A very simple backup script (little bit better)
#!/bin/bash
SRCD="/home/"
TGTD="/var/backups/"
OF=home-$(date +%Y%m%d).tgz
tar -cZf $TGTD$OF $SRCD

12.3 File re-namer

#!/bin/sh
# renna: rename multiple files according to several rules
# written by felix hudson Jan - 2000

#first check for the various 'modes' that this program has
#if the first ($1) condition matches then we execute that portion
of the
#program and then exit

# check for the prefix condition


if [ $1 = p ]; then

#we now get rid of the mode ($1) variable and prefix ($2)
prefix=$2 ; shift ; shift

# a quick check to see if any files were given


# if none then its better not to do anything than rename some
non-existent
# files!!

if [$1 = ]; then
echo "no files given"
exit 0
fi

# this for loop iterates through all of the files that we gave
the program
# it does one rename per file given
for file in $*
do
mv ${file} $prefix$file
done

#we now exit the program


exit 0
fi

# check for a suffix rename


# the rest of this part is virtually identical to the previous
section
# please see those notes
if [ $1 = s ]; then
suffix=$2 ; shift ; shift

if [$1 = ]; then
echo "no files given"
exit 0
fi

for file in $*
do
mv ${file} $file$suffix
done

exit 0
fi

# check for the replacement rename


if [ $1 = r ]; then
shift

# i included this bit as to not damage any files if the user does
not specify
# anything to be done
# just a safety measure

if [ $# -lt 3 ] ; then
echo "usage: renna r [expression] [replacement] files... "
exit 0
fi

# remove other information


OLD=$1 ; NEW=$2 ; shift ; shift

# this for loop iterates through all of the files that we give
the program
# it does one rename per file given using the program 'sed'
# this is a sinple command line program that parses standard
input and
# replaces a set expression with a give string
# here we pass it the file name ( as standard input) and replace
the nessesary
# text

for file in $*
do
new=`echo ${file} | sed s/${OLD}/${NEW}/g`
mv ${file} $new
done
exit 0
fi

# if we have reached here then nothing proper was passed to the


program
# so we tell the user how to use it
echo "usage;"
echo " renna p [prefix] files.."
echo " renna s [suffix] files.."
echo " renna r [expression] [replacement] files.."
exit 0

# done!

12.4 File renamer (simple)


#!/bin/bash
# renames.sh
# basic file renamer

criteria=$1
re_match=$2
replace=$3

for i in $( ls *$criteria* );
do
src=$i
tgt=$(echo $i | sed -e "s/$re_match/$replace/")
mv $src $tgt
done

13. When something goes wrong (debugging)


13.1 Ways Calling BASH
A nice thing to do is to add on the first line
#!/bin/bash -x

This will produce some intresting output information

14. About the document


Feel free to make suggestions/corrections, or whatever you think it would be
interesting to see in this document. I'll try to update it as soon as I can.

14.1 (no) warranty


This documents comes with no warranty of any kind. and all that

14.2 Translations
Italian: by William Ghelfi (wizzy at tiscalinet.it) is here

French: by Laurent Martelli is missed

Korean: Minseok Park http://kldp.org

Korean: Chun Hye Jin unknown

Spanish: unknow http://www.insflug.org

I guess there are more translations, but I don't have any info of them, if you have it,
please, mail it to me so I update this section.
14.3 Thanks to
 People who translated this document to other languages (previous section).
 Nathan Hurst for sending a lot of corrections.
 Jon Abbott for sending comments about evaluating arithmetic expressions.
 Felix Hudson for writing the renna script
 Kees van den Broek (for sending many corrections, re-writting usefull comands
section)
 Mike (pink) made some suggestions about locating bash and testing files
 Fiesh make a nice suggestion for the loops section.
 Lion suggested to mention a common error (./hello.sh: Command not found.)
 Andreas Beck made several corrections and coments.

14.4 History
New translations included and minor correcitons.

Added the section usefull commands re-writen by Kess.

More corrections and suggestions incorporated.

Samples added on string comparison.

v0.8 droped the versioning, I guess the date is enought.

v0.7 More corrections and some old TO-DO sections written.

v0.6 Minor corrections.

v0.5 Added the redirection section.

v0.4 disapperd from its location due to my ex-boss and thid doc found it's new place
at the proper url: www.linuxdoc.org.

prior: I don't rememeber and I didn't use rcs nor cvs :(

14.5 More resources


Introduction to bash (under BE) http://org.laol.net/lamug/beforever/bashtut.htm

Bourne Shell Programming http://207.213.123.70/book/


Vim Color Editor HOW-TO (Vi Improved
with syntax color highlighting)
Al Dev (Alavoor Vasudevan) [email protected]
v17.2, 28 June 2001

This document is a guide to quickly setting up the Vim color editor on Linux or Unix
systems. The information here will improve the productivity of programmers because
the Vim editor supports syntax color highlighting and bold fonts, improving the
"readability" of program code. A programmer's productivity improves 2 to 3 times
with a color editor like Vim. The information in this document applies to all operating
sytems where Vim works, such as Linux, Windows 95/NT, Apple Mac, IBM OSes, VMS,
BeOS and all flavors of Unix like Solaris, HPUX, AIX, SCO, Sinix, BSD, Ultrix etc.. (it
means almost all operating systems on this planet!)

1. Introduction
 1.1 Before you Install
 1.2 Install Vim on Redhat Linux
 1.3 Install Vim on GNU Debian Linux
 1.4 Install Vim on Unixes
 1.5 Install Vim on Microsoft Windows 95/NT
 1.6 Install Vim on VMS
 1.7 Install Vim on OS/2
 1.8 Install Vim on Apple Macintosh

2. Install Vim on Microsoft Windows 95/NT


 2.1 Install bash shell
 2.2 Edit bash_profile
 2.3 Setup Window colors
3. Setup gvim init files
 3.1 Sample gvimrc file
 3.2 Xdefaults parameters

4. Color Syntax init files


 4.1 Auto source-in method
 4.2 Manual method

5. VIM Usage
6. Vi companions
 6.1 Ctags for ESQL
 6.2 Ctags for JavaScript programs, Korn, Bourne shells
 6.3 Debugger gdb

7. Online VIM help


8. Vim Home page and Vim links
9. Vim Tutorial
 9.1 Vim Hands-on Tutorial
 9.2 Vi Tutorials on Internet

10. Vi Tutorial
 10.1 Cursor Movement Commands
 10.2 Repeat Counts
 10.3 Deleting Text
 10.4 Changing Text
 10.5 Yanking (Copying) Text
 10.6 Filtering text
 10.7 Marking Lines and Characters
 10.8 Naming Buffers
 10.9 Substitutions
 10.10 Miscellaneous "Colon Commands"
 10.11 Setting Options
 10.12 Key Mappings
 10.13 Editing Multiple Files
 10.14 Final Remarks

11. Vim Reference Card


 11.1 Vi states
 11.2 Shell Commands
 11.3 Setting Options
 11.4 Notations used
 11.5 Interrupting, cancelling
 11.6 File Manipulation
 11.7 Movement
 11.8 Line Positioning
 11.9 Character positioning
 11.10 Words, sentences, paragraphs
 11.11 Marking and returning
 11.12 Corrections during insert
 11.13 Adjusting the screen
 11.14 Delete
 11.15 Insert, change
 11.16 Copy and Paste
 11.17 Operators (use double to affect lines)
 11.18 Search and replace
 11.19 General
 11.20 Line Editor Commands
 11.21 Other commands

12. Related URLs


13. Other Formats of this Document
 13.1 Acrobat PDF format
 13.2 Convert Linuxdoc to Docbook format
 13.3 Convert to MS WinHelp format
 13.4 Reading various formats

14. Copyright Notice


1. Introduction
Vim stands for 'Vi Improved'. Vi is the most popular and powerful editors in the Unix
world. Vi is an abbreviation for "Visual" editor. One of the first editors was a line
editor called 'ed' (and 'ex'). The Visual editor like Vi was a vast improvement over line
editors like 'ed' (or 'ex'). The editors 'ed' and 'ex' are still available on Linux: see 'man
ed' and 'man ex'.

A good editor improves programmer productivity. Vim supports color syntax


highlighting of program code and also emphasises text using different fonts like
normal, bold or italics. A color editor like Vim can improve the productivity of
programmers by 2 to 3 times!! Programmers can read the code much more rapidly as
the code syntax is colored and highlighted.

1.1 Before you Install


Before you install Vim, please refer to the OS specific release notes and information
about compiling and usage of Vim at -

 Go to this location and look for files


os_*.txt http://cvs.vim.org/cgi-bin/cvsweb/vim/runtime/doc

If you do not have the Vim package (RPM, DEB, tar, zip) then download the Vim
source code by ftp from the official Vim site

 The home page of vim is at http://www.vim.org


 Mirror site in US is at http://www.us.vim.org
 Ftp site ftp://ftp.vim.org/pub/vim
 Or use one of the mirrors ftp://ftp.vim.org/pub/vim/MIRRORS

1.2 Install Vim on Redhat Linux


To use Vim install the following RPM packages on Redhat Linux -

rpm -i vim*.rpm
OR do this -
rpm -i vim-enhanced*.rpm
rpm -i vim-X11*.rpm
rpm -i vim-common*.rpm
rpm -i vim-minimal*.rpm
You can see the list of files the vim rpm installs by -

rpm -qa | grep ^vim | xargs rpm -ql | less


or
rpm -qa | grep ^vim | awk '{print "rpm -ql " $1 }' | /bin/sh | less

and browse output using j,k, CTRL+f, CTRL+D, CTRL+B, CTRL+U or using arrow keys,
page up/down keys. See 'man less'.

Note that the RPM packages for Redhat Linux use a Motif interface. If you have
installed the GTK libraries on your system, consider compiling Vim from the source
code for a clean GUI interface. For information on compiling Vim from the source
code, see "Install Vim on Unixes", below.

1.3 Install Vim on GNU Debian Linux


To install Vim on Debian Linux (GNU Linux), login as root and when connected to
internet type -

apt-get install vim vim-rt

It will download the latest version of vim, install it, configure it. The first package
listed is vim, the standard editor, compiled with X11 support, vim-rt is the vim
runtime, it holds all the syntax and help files.

1.4 Install Vim on Unixes


For other flavors of unixes like Solaris, HPUX, AIX, Sinix, SCO download the source
code file ( see Before you Install )

zcat vim.tar.gz | tar -xvf -


cd vim-5.5/src
./configure --enable-gui=motif
make
make install

1.5 Install Vim on Microsoft Windows 95/NT


See Install on MS Windows.

1.6 Install Vim on VMS


Download files

You will need both the Unix and Extra archives to build vim.exe for VMS. For using
Vim's full power you will need the runtime files as well. Get these files ( see Before
you Install )

You can download precompiled executables from: http://www.polarfox.com/vim

VMS vim authors are -

[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

Compiling

Unpack the Unix and Extra archives together into one directory. In the <.SRC>
subdirectory you should find the make file OS_VMS.MMS. By editing this file you
may choose between building the character, GUI and debug version. There are also
additional options for Perl, Python and Tcl support.

You will need either the DECSET mms utility or the freely available clone of it called
mmk (VMS has no make utility in the standard distribution). You can download mmk
from http://www.openvms.digital.com/freeware/MMK/

If you have MSS on your system, the command

> mms /descrip=os_vms.mms

will start building your own customised version of Vim. The equivalent command for
mmk is:
> mmk /descrip=os_vms.mms

Deploy

Vim uses a special directory structure to hold the document and runtime files:

vim (or wherever)


|- tmp
|- vim55
|----- doc
|----- syntax
|- vim56
|----- doc
|----- syntax
vimrc (system rc files)
gvimrc

Use:

> define/nolog device:[leading-path-here.vim] vim


> define/nolog device:[leading-path-here.vim.vim56] vimruntime
> define/nolog device:[leading-path-here.tmp] tmp

to get vim.exe to find its document, filetype, and syntax files, and to specify a
directory where temporary files will be located. Copy the "runtime" subdirectory of
the vim distribution to vimruntime.

Note: Logicals $VIMRUNTIME and $TMP are optional. Read more at :help runtime

Practical usage

Usually you want to run just one version of Vim on your system, therefore it is
enough to dedicate one directory for Vim. Copy all Vim runtime directory structure to
the deployment position. Add the following lines to your LOGIN.COM (in
SYS$LOGIN directory). Set up logical $VIM as:

> $ define VIM device: <path>

Set up some symbols:


> $ ! vi starts Vim in chr. mode.
> $ vi*m :== mcr device:<path>VIM.EXE

> $ !gvi starts Vim in GUI mode.


> $ gv*im :== spawn/nowait mcr device:<path>VIM.EXE -g

Create .vimrc and .gvimrc files in your home directory (SYS$LOGIN).

The easiest way is just rename example files. You may leave the menu file
(MENU.VIM) and files vimrc and gvimrc in the original $VIM directory. It will be
default setup for all users, and for users is enough just to have their own additions or
resetting in home directory in files .vimrc and .gvimrc. It should work without
problems.

Note: Remember, system rc files (default for all users) do not have the leading "." So,
system rc files are:

> VIM$:vimrc
> VIM$:gvimrc
> VIM$:menu.vim

and user's customised rc files are:

> sys$login:.vimrc
> sys$login:.gvimrc

You can check that everything is on the right place with the :version command.

Example LOGIN.COM:

> $ define/nolog VIM RF10:[UTIL.VIM]


> $ vi*m :== mcr VIM:VIM.EXE
> $ gv*im :== spawn/nowait mcr VIM:VIM.EXE -g
> $ set disp/create/node=192.168.5.223/trans=tcpip

Note: This set-up should be enough if you are working in a standalone server or
clustered environment, but if you want to use Vim as an internode editor, it should
suffice. You just have to define the "whole" path:
> $ define VIM "<server_name>[""user password""]::device:<path>"
> $ vi*m :== "mcr VIM:VIM.EXE"

as for example:

> $ define VIM "PLUTO::RF10:[UTIL.VIM]"


> $ define VIM "PLUTO""ZAY mypass""::RF10:[UTIL.VIM]" ! if passwd
required

You can also use $VIMRUNTIME logical to point to proper version of Vim if you
have multiple versions installed at the same time. If $VIMRUNTIME is not defined
Vim will borrow value from $VIM logical. You can find more information about
$VIMRUNTIME logical by typing :help runtime as a Vim command.

GUI mode questions

VMS is not a native X window environment, so you can not start Vim in GUI mode
"just like that". But it is not too complicated to get a running Vim.

1) If you are working on the VMS X console:


Start Vim with the command:

> $ mc device:<path>VIM.EXE -g

or type :gui as a command to the Vim command prompt. For more info :help
gui

2) If you are working on other X window environment as Unix or some remote X


VMS console. Set up display to your host with:

> $ set disp/create/node=<your IP address>/trans=<transport-name>

and start Vim as in point 1. You can find more help in VMS documentation or
type: help set disp in VMS prompt.
Examples:

> $ set disp/create/node=192.168.5.159 ! default trans is


DECnet
> $ set disp/create/node=192.168.5.159/trans=tcpip ! TCP/IP network
> $ set disp/create/node=192.168.5.159/trans=local ! display on the same
node
Note: you should define just one of these. For more information type $help set disp in
VMS prompt.

1.7 Install Vim on OS/2


Read the release notes for Vim on OS/2, see Before you Install .

At present there is no native PM version of the GUI version of vim: The OS/2 version
is a console application. However, there is now a Win32s-compatible GUI version,
which should be usable by owners of Warp 4 (which supports Win32s) in a Win-OS/2
session. The notes in this file refer to the native console version.

To run Vim, you need the emx runtime environment (at least rev. 0.9b). This is
generally available as (ask Archie about it):

emxrt.zip emx runtime package

1.8 Install Vim on Apple Macintosh


Read the release notes for Vim on OS/2, see Before you Install .

The author of Vim on Mac (old version vim 3.0) is

Eric Fischer
5759 N. Guilford Ave
Indianapolis IN 46220 USA

Email to [email protected]

Mac Bug Report When reporting any Mac specific bug or feature change, makes sure
to include the following address in the "To:" or "Copy To:" field.

[email protected]

Vim compiles out of the box with the supplied CodeWarrior project when using
CodeWarrior 9. If you are using a more recent version (e. g. CW Pro) you have to
convert the project first. When compiling Vim for 68k Macs you have to open the
"size" resource in ResEdit and enable the "High level events aware" button to get drag
and drop working. You have to increase the memory partition to at least 1024 kBytes
to prevent Vim from crashing due to low memory.

vim:ts=8:sw=8:tw=78:

2. Install Vim on Microsoft Windows 95/NT


For Windows 95/NT, download the Vim zip file. For Windows 95/NT you must
download TWO zip files -

 Runtime support file vim*rt.zip


 Vim command file vim*56.zip. Where Vim version is 5.6.

Get these two zip files ( see Before you Install ) Unpack the zip files using the
Winzip http://www.winzip.com. Both the zip files (vim*rt.zip and vim*56.zip) must
be unpacked in the same directory like say c:\vim.

For Windows 95/98, set the environment variable VIM in autoexec.bat by adding this
line -

set VIM=c:\vim\vim56

For Windows NT, add the environment variable VIM to the Control Panel | System |
Environment | System Properties dialog:

VIM=c:\vim\vim56

The VIM variable should point to whereever you installed the vim56 directory. You
can also set your PATH to include the gvim.exe's path.

You may need to logoff and relogin to set your environment. At an MS-DOS prompt
type -

set vim
And you should see - VIM=c:\vim\vim56

Create a short-cut on to your desktop by click-and-drag from c:\vim\vim56\gvim.exe.


Copy the gvimrc_example file to the $VIM\_gvimrc. In my case it is c:\vim\vim56\
_gvimrc.

copy c:\vim\vim56\gvimrc_example $VIM\_gvimrc

2.1 Install bash shell


In order make MS Windows 2000/NT/95/98 even more user-friendly, install the bash
shell (Bourne Again Shell).
Installhttp://sources.redhat.com/cygwin/setup.exe (Cygwin-setup program) and select
bash and other common utilities. The CygWin main site is
athttp://sources.redhat.com/cygwin. With CygWin the Windows 2000 computer will
look like Linux/Unix box!! And combined with gvim editor, the Windows 2000 gives
programmers more power.

2.2 Edit bash_profile


After installing the Cygwin, insert some useful aliases in /.bash_profile file. Open a
cygwin window and at bash prompt -

bash$ cd $HOME
bash$ gvim .bash_profile
set -o vi
alias ls='ls --color '
alias cp='cp -i '
alias mv='mv -i '
alias rm='rm -i '
alias vi='gvim '
alias vip='gvim ~/.bash_profile & '
alias sop='. ~/.bash_profile '
alias mys='mysql -uroot -p '
PATH=$PATH:"/cygdrive/c/Program Files/mysql/bin"

With color ls, when you do ls you will see all the directory names and files in different
colors (it looks great!!). With set -o vi, you can use the command line history editing
just as in linux.
2.3 Setup Window colors
The default background color of MS DOS prompt window is black and white text.
You must change the color, fontsize and window size to make it more pleasing. On
MS Windows 2000, click on button Start->Run and type "cmd" and hit return. On MS
Windows 95/98/NT click on Start->Programs->MSDOS Prompt which will bring up
MSDOS window. Right click on the top left corner of the MSDOS prompt window
and select properties. Select color background and enter R=255, G=255, B=190 (red,
green, blue) for lightyellow background and text foreground color to black (R=0,
G=0, B=0). This sets background to light yellow and text foreground to black and this
combination is most pleasing to human eyes. If you have problems with colors in
cygwin bash window when doing 'man ls', set the text color to "marune".

For Windows95 see Color for MS-DOS prompt window.

3. Setup gvim init files


To enable the syntax color highlighting you MUST copy the gvimrc file to your home
directory. This will also put the "Syntax" Menu with gvim command. You can click
on Syntax Menu and select appropriate languages like C++, Perl, Java, SQL, ESQL
etc..

cd $HOME
cp /usr/doc/vim-common-5.3/gvimrc_example ~/.gvimrc

Comment lines in .gvimrc begin with double-quotes ("). You can customize gvim by
editing the file $HOME/.gvimrc and put the following lines -

" This line is a comment .... one which begins with double-quotes
" The best is the bold font, try all of these and pick one....
set guifont=8x13bold
"set guifont=9x15bold
"set guifont=7x14bold
"set guifont=7x13bold
"
" Highly recommended to set tab keys to 4 spaces
set tabstop=4
set shiftwidth=4
"
" The opposite is 'set wrapscan' while searching for strings....
set nowrapscan
"
" The opposite is set noignorecase
set ignorecase
set autoindent
"
" You may want to turn off the beep sounds (if you want quite) with visual
bell
" set vb

" Source in your custom filetypes as given below -


" so $HOME/vim/myfiletypes.vim

It is very strongly recommended that you set the tabstop to 4 and shiftwidth to 4.
The tabstop is the number of spaces the TAB key will indent while editing with gvim.
The shiftwidth is the number of spaces the lines will be shifted with ">>" or "<<" vi
commands. Refer to Vi tutorials Vim Tutorial for more details.

To see the list of available fonts on Linux/Unix see the command xlsfonts. Type -

bash$ xlsfonts | less


bash$ xlsfonts | grep -i bold | grep x
bash$ man xlsfonts

3.1 Sample gvimrc file


You can change the settings like color, bold/normal fonts in your $HOME/.gvimrc
file. It is very strongly recommended that you set the background color
tolightyellow or white with black foreground. Ergonomics says that best background
color is lightyellow or white with black foreground. Hence change the variable 'guibg'
in your $HOME/.gvimrc file as follows:

highlight Normal guibg=lightyellow

The sample gvimrc from /usr/doc/vim-common-5.3/gvimrc_example is as follows:

" Vim
" An example for a gvimrc file.
" The commands in this are executed when the GUI is started.
"
" To use it, copy it to
" for Unix and OS/2: ~/.gvimrc
" for Amiga: s:.gvimrc
" for MS-DOS and Win32: $VIM\_gvimrc

" Make external commands work through a pipe instead of a pseudo-tty


"set noguipty

" set the X11 font to use. See 'man xlsfonts' on unix/linux
" set guifont=-misc-fixed-medium-r-normal--14-130-75-75-c-70-iso8859-1
set guifont=8x13bold
"set guifont=9x15bold
"set guifont=7x14bold
"set guifont=7x13bold
"
" Highly recommended to set tab keys to 4 spaces
set tabstop=4
set shiftwidth=4
"
" The opposite is 'set wrapscan' while searching for strings....
set nowrapscan
"
" The opposite is set noignorecase
set ignorecase
"
" You may want to turn off the beep sounds (if you want quite) with visual
bell
" set vb

" Source in your custom filetypes as given below -


" so $HOME/vim/myfiletypes.vim

" Make command line two lines high


set ch=2

" Make shift-insert work like in Xterm


map <S-Insert> <MiddleMouse>
map! <S-Insert> <MiddleMouse>

" Only do this for Vim version 5.0 and later.


if version >= 500

" I like highlighting strings inside C comments


let c_comment_strings=1

" Switch on syntax highlighting.


syntax on

" Switch on search pattern highlighting.


set hlsearch

" For Win32 version, have "K" lookup the keyword in a help file
"if has("win32")
" let winhelpfile='windows.hlp'
" map K :execute "!start winhlp32 -k <cword> " . winhelpfile <CR>
"endif
" Hide the mouse pointer while typing
set mousehide

" Set nice colors


" background for normal text is light grey
" Text below the last line is darker grey
" Cursor is green
" Constants are not underlined but have a slightly lighter background
highlight Normal guibg=grey90
highlight Cursor guibg=Green guifg=NONE
highlight NonText guibg=grey80
highlight Constant gui=NONE guibg=grey95
highlight Special gui=NONE guibg=grey95

endif

See also sample vimrc used for console mode vim command from /usr/doc/vim-
common-5.3/vimrc_example.

3.2 Xdefaults parameters


You can set some of the Vim properties in Xdefaults file.

WARNING: Do not set Vim*geometry as it will break the gvim menu,


use Vim.geometry instead.

Edit the $HOME/.Xdefaults file and add the following lines:

! GVim great Colors.


Vim*useSchemes: all
Vim*sgiMode: true
Vim*useEnhancedFSB: true
Vim.foreground: Black
!Vim.background: lightyellow2
Vim*background: white
! Do NOT use Vim*geometry , this will break the menus instead
! use Vim.geometry. Asterisk between Vim and geometry is not allowed.
! Vim.geometry: widthxheight
Vim.geometry: 88x40
!Vim*font: -misc-fixed-medium-r-normal--20-200-75-75-c-100-
iso8859-15-*5
Vim*menuBackground: yellow
Vim*menuForeground: black

In order for this change to take effect, type -


xrdb -merge $HOME/.Xdefaults
man xrdb

You can also edit the ~/.gvimrc file to change the background colors

gvim $HOME/.gvimrc
The best background color is lightyellow or white, with black foreground.
highlight Normal guibg=lightyellow

4. Color Syntax init files


4.1 Auto source-in method
This section below is obtained from gvim session by typing 'help syntax' -

bash$ gvim some_test


:help syntax

Click on the menu Window=>Close_Others to close other Window. And then do


CTRL+] on 'Syntax Loading Procedure' menu which will take you there. (Use
CTRL+T to rewind and go back).

If a file type you want to use is not detected, then there are two ways to add
it. Method 1: You can modify the $VIMRUNTIME/filetype.vim file, but this is not
recommended as it will be overwritten when you install a new version of Vim.

Method 2: Create a file in $HOME/vim/myfiletypes.vim and put these lines in it -

"
*************************************************************
" Filename : $HOME/vim/myfiletypes.vim
" See the document by typing :help autocmd within vim session
" see also the doc at /usr/share/vim/doc/autocmd.txt
" This file will setup the autocommands for new filetypes
" using the existing syntax-filetypes.
" For example when you open foo.prc it will use syntax of plsql
" Basically does :set filetype=prc inside vim
" Add a line in $HOME/.gvimrc as below:
" so $HOME/vim/myfiletypes.vim
"
*************************************************************
augroup filetype
au!
au! BufRead,BufNewFile *.phc set filetype=php
au! BufRead,BufNewFile *.mine set filetype=mine
au! BufRead,BufNewFile *.xyz set filetype=drawing
au! BufRead,BufNewFile *.prc set filetype=plsql
augroup END

Then add a line in your $HOME/.vimrc and $HOME/.gvimrc file to source in the file
"myfiletypes.vim". (CAUTION: You MUST put this in both vimrc and gvimrc files
in order for this to work) Example:
so $HOME/vim/myfiletypes.vim

NOTE: Make sure that you set "so myfiletypes.vim" before switching on file type
detection. This is must be before any ":filetype on" or ":syntax on" command.

See the documentation on autocommand at -

 :help autocmd (within a vim editing session)


 See also the doc at /usr/share/vim/doc/autocmd.txt

Your file will then be sourced in after the default FileType autocommands have been
installed. This allows you to overrule any of the defaults, by using ":au!" to remove
any existing FileType autocommands for the same pattern. Only the autocommand to
source the scripts.vim file is given later. This makes sure that your autocommands in
"myfiletypes.vim" are used before checking the contents of the file.

4.2 Manual method


Instead of using "Syntax" menu you can also manually source in the syntax file. Edit
the file with gvim and at : (colon) command give 'so' command. For example -

gvim foo.pc
:so $VIM/syntax/esqlc.vim

The syntax source files are at /usr/share/vim/syntax/*.vim. Vim supports more than
120 different syntax files for different languages like C++, PERL, VHDL,
JavaScript,...and so on!!

Each syntax file supports one or more default file name extensions, for example,
JavaScript syntax file supports the *.js extension. If you happen to use an extension
that conflicts with another default syntax file (such as adding JavaScript to a *.html
file) than you can source in the additional syntax file with the command :so
$VIM/syntax/javascript.vim. To avoid all of this typing, you can create a soft link like
-

ln -s $VIM/syntax/javascript.vim js
gvim foo.html (... this file contains javascript functions and HTML)
:so js

5. VIM Usage
You can use Vim in two modes - one with GUI and other without GUI. To use GUI
use command -

gvim foo.cpp

To use non-gui mode give -


vim foo.cpp
OR plain vanilla mode
vi foo.cpp

It is very strongly recommended that you always use gvim instead of vim, since GUI
mode with colors will definitely improve your productivity.

GUI mode gvim provides the following -

 You can mark the text using the mouse to do cut, copy and paste.
 You can use the Menu bar which has - File, Edit, Window, Tools, Synatx and
Help buttons.
 Also in near future in gvim - a second menu bar will display the list of files
being edited, and you can switch files by clicking on the filenames, until then
you can use vi commands - :e#, :e#1, :e#2, :e#3, :e#4, ....so on to select the
files.

6. Vi companions
Generally Vim is used in conjunction with other powerful tools
like ctags and gdb. ctags is for very rapid navigation through millions of lines of
"C/C++" code and gdb is for debugging the "C/C++" code. A brief introduction of
these two indispensable commands will be given in this chapter.
ctags is the most powerful command available for coding C, C++, Java, Perl,
Korn/Bourne shell scripts or Fortran. Developers very extensively use ctags to
navigate through thousands of functions within C/C++ programs. See 'man ctags' on
Unix. It is very important that you learn how to use ctags to develop programs in C
or C++, Java, etc.. Navigation is the single most important task while doing
development of C or C++ code. Using ctags you can very quickly read the code by
jumping from a calling line to the called function, drill down deeper into nested
function calls, and unwind back all the way up to the top. You can go back and forth
from function to function very quickly.

Without NAVIGATION you will be completely lost! ctags is like the magnetic
COMPASS needle for the programmers.

Usage of ctags :

ctags *.cpp
gvim -t foo_function
gvim -t main

This will edit the C++ program file which contains the function foo_function() and will
automatically place the cursor on the first line of the function foo_function(). The
second command takes you to the line with the main() function definition.

Inside the Vim editor, you can jump to a function by typing : (colon) tag < function
name >as below -

:tag sample_function

This will place the cursor on first line of sample_function()

If you want to jump into the function from a line in file which contains the function
name, place the cursor just before the function name and press CTRL+](press control
key and left-square-bracket key simultaneously).

// example code
switch(id_number) {
Case 1:
if ( foo_function( 22, "abcef") == 3 )
^
|
|
|
Place the cursor here (just before foo_function) and press
CTRL+]
This takes you to the function named "foo_function".
To come back to this line press CTRL+t

To go back to the calling line press CTRL+t (Control key and letter 't' together). Keep
pressing CTRL+t to unwind and go to the first line where you started the navigation.
That is you can keep pressing CTRL+] and then keep pressing CTRL+t to go back. You
can repeat these as many times as you want to have complete navigation through all
the functions of C or C++.

6.1 Ctags for ESQL


Since ctags does not directly support the Embedded SQL/C (ESQL) language, the
following shell script can be used to create tags for esql. ESQL/C is database SQL
commands embedded inside the "C" programs. Oracle's ESQL/C is called Pro*C and
Sybase, Informix have ESQL/C and PostgreSQL has product "ecpg".

Save this file as "sqltags.sh" and do chmod a+rx tags_gen.sh.

#!/bin/sh

# Program to create ctags for ESQL, C++ and C files


ESQL_EXTN=pc
tag_file1=tags_file.1
tag_file2=tags_file.2

which_tag=ctags

rm -f $tag_file1 $tag_file2 tags

aa=`ls *.$ESQL_EXTN`
#echo $aa
for ii in $aa
do
#echo $ii
jj=`echo $ii | cut -d'.' -f1`
#echo $jj

if [ ! -f $jj.cpp ]; then
echo " "
echo " "
echo "***********************************************"
echo "ESQL *.cpp files does not exist.. "
echo "You must generate the *.cpp from *.pc file"
echo "using the Oracle Pro*C pre-compiler or Sybase"
echo "or Informix esql/c pre-compiler."
echo "And then re-run this command"
echo "***********************************************"
echo " "
exit
fi

rm -f tags
$which_tag $jj.cpp
kk=s/$jj\.cpp/$jj\.pc/g

#echo $kk > sed.tmp


#sed -f sed.tmp tags >> $tag_file1

#sed -e's/sample\.cpp/sample\.pc/g' tags >> $tag_file1


sed -e $kk tags >> $tag_file1
done

# Now handle all the C++/C files - exclude the ESQL *.cpp files
rm -f tags $tag_file2
bb=`ls *.cpp *.c`
aa=`ls *.$ESQL_EXTN`
for mm in $bb
do
ee=`echo $mm | cut -d'.' -f1`
file_type="NOT_ESQL"
# Exclude the ESQL *.cpp and *.c files
for nn in $aa
do
dd=`echo $nn | cut -d'.' -f1`
if [ "$dd" = "$ee" ]; then
file_type="ESQL"
break
fi
done

if [ "$file_type" = "ESQL" ]; then


continue
fi

rm -f tags
$which_tag $mm
cat tags >> $tag_file2
done

mv -f $tag_file2 tags
cat $tag_file1 >> tags
rm -f $tag_file1

# Must sort tags file for it work properly ....


sort tags > $tag_file1
mv $tag_file1 tags
6.2 Ctags for JavaScript programs, Korn, Bourne shells
The shell script given below can be used to generate tags for a very large variety of
programs written in JavaScript, PHP/FI scripts, Korn shell, C shell, Bourne shell and
many others. This is a very generic module.

Save this file as tags_gen.sh and do chmod a+rx tags_gen.sh.

#!/bin/sh

tmp_tag=tags_file
tmp_tag2=tags_file2

echo " "


echo " "
echo " "
echo " "
echo " "
echo "Generate tags for ...."
while :
do
echo " Enter file extension for which you want to generate tags."
echo -n " File-extension should be like sh, js, ksh, etc... : "
read ans

if [ "$ans" == "" ]; then


echo " "
echo "Wrong entry. Try again!"
else
break
fi
done

\rm -f $tmp_tag

aa=`ls *.$ans`

for ii in $aa
do
jj=`echo $ii | cut -d'.' -f1`
#echo $jj
cp $ii $jj.c
ctags $jj.c
echo "s/$jj.c/$ii/g" > $tmp_tag2
sed -f $tmp_tag2 tags >> $tmp_tag
\rm -f tags $jj.c
done

sort $tmp_tag > tags


\rm -f $tmp_tag $tmp_tag2

6.3 Debugger gdb


You would be using gdb extensively along with Vi. Debugging is the most important
aspect of programming as the major cost of software projects goes into debugging and
testing.

To debug C++/C programs use 'gdb' tool. See 'man gdb'. You must compile your
programs with -g3 option like
gcc -g3 foo.c foo_another.c sample.c

To set up easy aliases do -


Setup an alias in your ~/.bash_profile
alias gdb='gdb -directory=/home/src -directory=/usr/myname/src '
Give -
gdb foo.cpp
gdb> dir /hom2/another_src
This will add to file search path
gdb> break 'some_class::func<TAB><TAB>
This will complete the function name saving you typing time... and will
output like -
gdb> break 'some_class::function_foo_some_where(int aa, float bb)'

Pressing TAB key twice is the command line completion, which will save you lots of
typing time. This is one of the most important technique of using gdb.

To get online help do -


gdb> help
Gives online help
gdb> help breakpoints
Gives more details about breakpoints.

To set breakpoints and do debugging


unixprompt> gdb exe_filename
gdb> b main
This will put breakpoint in main() function
gdb> b 123
This will put breakpoint in line 123 of the current file
gdb> help breakpoints
Gives more details about breakpoints.

To analyze the core dumps do


unixprompt> gdb exe_filename core
gdb> bt
Gives backtrace of functions and line numbers where the program failed
gdb> help backtrace
Gives more details about backtrace.

You can also use GUI version of gdb called xxgdb.

See also gdb interface to Vim at http://www.lxlinux.com/gdbvim.tgz.

Memory leak tools -

 Freeware Electric Fence on linux cd,


 Commercial tools Purify http://www.rational.com
 Insure++ http://www.insure.com

7. Online VIM help


See the online man pages. At unix shell prompt type 'man vim' and 'man gvim'.

Or inside the gvim session type :help to get the help page. See also Vim Tutorial To
see the settings type :set all or :set. To see list of options type :options. To see topics
on set type :help set.
VIM - main help file

Move around: Use the cursor keys, or "h" to go left,


"j" to go down, "k" to go up, "l" to go right.
":1" takes you to 1st line of page
":n" takes you to nth line of page
"<SHIFT>g" takes you to bottom of page
":/someword/ will search for "someword" in doc

Close this window: Use ":q<Enter>".

Jump to a subject: Position the cursor on a tag between |bars| and hit
CTRL-].

With the mouse: ":set mouse=a" to enable the mouse (in xterm or GUI).
Double-click the left mouse button on a tag between |
bars|.

jump back: Type CTRL-T or CTRL-O.

Get specific help: It is possible to go directly to whatever you want help


on, by giving an argument to the ":help" command |:help|.
It is possible to further specify the context:
WHAT PREPEND EXAMPLE ~
Normal mode commands (nothing) :help x
Visual mode commands v_ :help v_u
Insert mode commands i_ :help i_<Esc>
command-line commands : :help :quit
command-line editing c_ :help c_<Del>
Vim command arguments - :help -r
options ' :help 'textwidth'

list of documentation files:

|howto.txt| how to do the most common things


|intro.txt| introduction to Vim
|index.txt| alphabetical index for each mode
|autocmd.txt| automatically executing commands on an event
|change.txt| delete and replace text

8. Vim Home page and Vim links


The home page of vim is at http://www.vim.org and mirror site in US is
at http://www.us.vim.org

Vim FAQ is at http://www.grafnetix.com/~laurent/vim/faq.html and


at http://www.vim.org/faq

Eli's Vim Page at http://www.netusa.net/~eli/src/vim.html

The Vi Lovers Home Page http://www.cs.vu.nl/~tmgil/vi.html

Vim Reference Guide at http://scisun.sci.ccny.cuny.edu/~olrcc/vim/

Vim mailing list


at http://www.findmail.com/listsaver/vimannounce.html and http://www.vim.org/
mail.html

Mailing list archives are kept at:

 http://www.egroups.com/group/vim
 http://www.egroups.com/group/vimdev
 http://www.egroups.com/group/vimannounce

Vim macros http://www.grafnetix.com/~laurent/vim/macros.html

9. Vim Tutorial
9.1 Vim Hands-on Tutorial
On Linux system see the tutorial at /usr/doc/vim-common-5.*/tutor, on other unix
systems go to directory where vim is installed and look for doc directory.

bash$ cd /usr/doc/vim-common*/tutor
bash$ less README.txt
bash$ cp tutor $HOME
bash$ cd $HOME
bash$ less tutor

9.2 Vi Tutorials on Internet


 Purdue University http://ecn.www.ecn.purdue.edu/ECN/Documents/VI/
 Quick Vi tutorial http://linuxwww.db.erau.edu/LUG/node165.html
 Advanced Vi
tutorial http://www.yggdrasil.com/bible/bible-src/user-alpha-4/guide/
node171.html
 Tutorials http://www.cfm.brown.edu/Unixhelp/vi_.html
 Tutorials http://www.linuxbox.com/~taylor/4ltrwrd/section3_4.html
 Unix world online vi
tutorial http://www.networkcomputing.com/unixworld/unixhome.html
 Univ of Hawaii tutorial http://www.eng.hawaii.edu/Tutor/vi.html
 InfoBound http://www.infobound.com/vi.html
 Cornell Univ http://www.tc.cornell.edu/Edu/Tutor/Basics/vi/
 Vi Lovers home page: http://www.cs.vu.nl/~tmgil/vi.html
 After Sept 2000, will moveto http://www.thomer.com/thomer/vi/vi.html
 Beginner's Guide to
vi http://www.cs.umr.edu/unixinfo/general/packages/viguide.html
 vi Help file http://www.vmunix.com/~gabor/vi.html
 vim FAQ http://www.math.fu-berlin.de/~guckes/vim/faq/

There are many Vi Tutorials on internet. In Yahoo (Lycos, excite or Hotbot) enter "Vi
Tutorial" in search field and search engine will return many pointers.

10. Vi Tutorial
In this tutorial, we describe some "advanced" vi concepts and commands, so you can
appreciate the power of vi and so you decide how to build your knowledge
of vi commands. Nearly all vi references list the available commands, but many don't
bother to discuss how the commands interrelate; this topic is the main purpose of this
tutorial.

10.1 Cursor Movement Commands


The vi cursor movement commands allow you to position the cursor in the file and/or
on the screen efficiently, with a minimum number of keystrokes. There are oodles of
cursor movement commands - don't try memorizing them all at once! Later, we'll see
that much of the power of vi comes from mixing cursor movement commands with
other commands to delete, change, yank (copy), and filter text.

Please edit a large text file (say, wknight) so you can experiment with each command
as it is described. Keep in mind these commands will only work in Command Mode,
not Insert Mode; if you start getting your "commands" in your text, press the ESC key
to return to Command Mode.

 cursor keys : As we've seen, cursor keys move by single character amounts
left, down, up, and right. Movement above the top of the file, below the bottom,
to the right of the end of a line, or left of the beginning is not allowed (no line
wrapping).
 hjkl : When vi was written (around 1978), many terminals on UNIX systems
did not have cursor keys! h, j, k, and l were chosen as commands to move left,
down, up, and right, respectively. Try them! Most vi diehards prefer these to
the cursor keys because
o (a) they are in the same place on all keyborads, and
o (b) they fit nicely under the fingers, unlike most cursor keys, which are
arranged in a box or "T" or some other nonlinear shape.

Why h, j, k, and l? Well, in the ASCII character set, CTRL-H is backspace


(moves left), CTRL-J is linefeed (moves down), and, of course, k and l are next
to h and j, so you see, they're mnemonic.

 0 : ("zero", not "oh") Move to the beginning of current line. (To try this and the
next few commands, use the cursor keys or h j k l to move to an indented text
line that contains few "e" characters. If you can't find an indented line in your
file, create one by inserting a few space characters at the beginning of a line.)
 ^ : Move to first non-white character of current line. (For indented line, 0 and ^
are different.)
 $ : Move to last character of current line.
 tC : Move to (but not on) next character c in current line. (Press 0, then press
te. This will move to the first e in the curent line.)
 fC : Find (move on top of) next character c in current line. (Press fe, and the
cursor will find - that is, move on top - the next e in the current line.)
 TC : Move to (but not on) the previous character c in current line (Press $, then
Te.)
 FC : Find (move on top of) the previous character c in current line. (Press Fe.)
 n| : Move to column n in current line. (Try 20 |. The digits 2 and 0 will not be
displayed as you type them, but when you press | the cursor will move to
column 20.) Try some experiments with t f T F | . When you do something
illegal, vi will beep your terminal.
 w : Forward to beginning of next "small" word ( a "small" word consists of
unbroken alphanumeric characters or punctuation characters, but not mixed
alphanumeric and punctuation). Try tapping w a dozen times or so - note what
happens at punctuation.
 W : Forward to beginning of next "big" word (alphanumeric and punctuation
mixed). Try W a dozen times or so.
 b : Backward to beginning of "small" word.
 B : Backward to beginning of "big" word.
 e : Forward to end of "small" word.
 E : Forward to end of "big" word.
 + Return : Move to first non-white space character on next line. (+ and the
Return key have the same effect.)
 - : Move to first non-white space character on previous line.
 ) : Move to the end of sentence. (A sentence ends either at a blank line or at a
period or examination mark followed by two space characters or at the end of a
line. A period or exclamation mark followed by one space character does not
end a sentence; this is correct behaviour, according to traditional rules of how
sentences should appear in typed documents, but often appears wrong to those
who have never suffered through a formal typing class.)
 ( : Move to beginning of sentence.
 } : Move to end of paragraph. (Paragraphs are seperated with blank lines,
by vi's definition.)
 { : Move to beginning of paragraph.
 H : Move to home position (top line) on the screen
 M : Move to middle line on the screen.
 L : Move to last line on the screen.
 nG : Move to line n. If n is not given, move to the last line in the file. (Try 15G
to move to line 15, for example. The CTRL-G command displays the name of
the file, some status information, and the current line number. To move to the
top of the file: 1G)
 CTRL-d : Scroll down half-screen (see note).
 CTRL-u : Scroll up half-screen (see note).
 CTRL-f : Move forward one-screen (see note).
 CTRL-b : Move backward one-screen (see note).
 Note : These four scrolling/paging commands cannot be used with the delete,
change, yank, or filter commands.
 /reg_exp : Move to next occurrence of the regular expression reg_exp When
you press /, the cursor drops to the lower left corner of the screen and waits for
you to type in the regular expression. Press the Return key to finish; vi then
searches forward for the next occurrence of the regular expression. For
example, press /the followed by Return. This moves forward to the next
occurrence of the, perhaps imbedded in the middle of some longer word (other,
weather, etc.). If you just press / and then Return, vi searches for the next
occurrence of whatever the last regular expression was that you searched for.
 n : Has the same effect as pressing / and then Return; i.e., searches for the next
occurrence of whatever the last regular expression was that you searched for.
 ?reg_exp : Searches backward, rather than forward. If no reg_exp is given, it
searches for the last regular expression that was entered. Both / and ? wrap
around, so searching "below" the bottom or "above" the top of the file is legal.
 N : Same as pressing ? and then Return.

10.2 Repeat Counts


Many of the movement commands discussed above can be preceded with a repeat
count; the movement is simply repeated the given number of times:

 3w : Move forward three words


 5k : Move up four characters
 3fa : Find the third succeeding a in current line
 6+ : Move down six lines

For some commands, the "repeat counts" has special meaning:

 4H : Move to Line 4 on the screen (home plus 3)


 8L : Move to the eigth line from the bottom of the screen
 3$ : Move to the end of the third line down

For some commands (e.g., ^) the repeat count is ignored; for others (e.g., / and ? ) it is
illegal

10.3 Deleting Text


We've seen that dd deletes the current line. This can be used with a repeat count: 3dd
deletes three lines, the current line, and the two following lines.

The d command can be used as a "prefix" on most of the movement commands above
to delete nearly arbitrary chunks of text. When used with d, the movement commands
are called target specifiers. d can be given a repeat count. (As you try these
experiments, remember to press u after each command to undo the deletion).

 dw : Delete "small" word forward


 d3w : Delete three "small" words forward
 3dw : Three times, delete "small" word forward
 3d3w : Three times, delete three "small" words forward (that is, delete nine
"small" words forward)
 d+ : Delete current line and next line down
 d/the : Delete from current character up to but not including the next
occurrence of the pattern the.
 d$ : Delete to end of line
 d0 : Delete to beginning of line
 d30G : Delete from the curent line to and including Line 30
 dG : Delete from current line to and including last line
 d1G : Delete from current line to and including Line 1

To delete single characters, use x. x can be given a repeat count:

 15x : Delete current and 14 following characters

x is actually just an abbreviation of d1; that is, delete one character right.

10.4 Changing Text


The c command is similar to d, except it toggles vi into Insert Mode, allowing the
original (unwanted) text to be changed to something else.

For example, put the cursor on the beginning of a word (press w to get to the
beginning of the next word). Then, press cw to change that word. On the screen, the
last character in the word being changed will be replaced with a $ symbol indicating
the boundary of the change; type in a new word (you will overwrite the original word
on the screen) and press the ESC key when done. Your input may be longer or shorter
than the word being changed.

Put the cursor at the beginning of a line containing at least three words, and try c3w to
change three words. Try c$ to change to the end of the current line. In all cases where
the change affects only the current line, the boundary of the change is indicated with
$.

When a change affects more than just the current line, vi deletes the original text from
the screen and toggles into Insert Mode. For example, try c3+ to change the current
and the next three lines; vi deletes the four original lines from the screen and toggles
into Insert Mode in a new blank line. As usual, press the ESC key when you have
finished entering your new text.

Some other change commands:

 cc : Change current line


 5cc : Change five lines (current and next four)
 c/the : Change from current character up to but not including the next
occurrence of the pattern the
 c$ : Change to end of line
 c30G : Change from the current line to and including Line 30
 cG : Change from curernt line to and including last line
 c1G : Change from curernt line to and including Line 1

10.5 Yanking (Copying) Text


The y command yanks a copy of text into a buffer; the yanked text can then be put (or
pasted) elsewhere in the file using p or P.

The simplest form of yank is yy to yank the current line; after yy, try p to put a copy
of the yanked line after the cursor. Following yy, you can make as many copies of the
yanked line as you want by moving up and down in the file and pressing p.

To copy multiple lines, try, for example, 5yy (yank the current and next four lines). p
puts a copy of the yanked lines after the cursor; the sequence 5yyp "works" but it
probably doesn't do what you would like. The P command is like p, but puts a copy of
the yanked text ahead of the cursor; try the sequence 5yyP.

Other yank commands:

 y3w : Yank three words


 y$ : Yank to end of current line
 y1G : Yank from current line to and including Line 1

10.6 Filtering text


The filter command !, prompts for the name of a UNIX command (which should be a
filter), then passes selected lines through the filter, replacing those selected line in
the vi buffer with the output of the filter command. vi's ability to pass nearly arbitrary
chunks of text through any UNIX filter adds incredible flexibility to vi, at no
"additional cost" in size or performance to vi itself.

Some examples will help illustrate. Create a line in your file containing just the word
who and absolutely no other text. Put the cursor on this line, and press !!This
command is analogous to dd, cc, or yy, but instead of deleting, changing, or yanking
the current line, it filters the current line. When you press the second !, the cursor
drops down to the lower left corner of the screen and a single ! is displayed,
prompting you to enter the name of a filter. As the filter name, type sh and press the
Return key. sh (the Bourne shell) is a filter! It reads standard input, does some
processing of its input (that is, executes commands), and sends its output (the output
of those commands) to standard output. Filtering the line containing who through sh
causes the line containing who to be replaced with a list of the current users on the
system - right in your file!

Try repeating this process with date. That is, create a line containing nothing but the
word date, then put the cursor on the line, and press !!sh and the Return key. The line
containing date is replaced with the output of the date command.

Put your cursor on the first line of the output of who. Count the number of lines.
Suppose, for example, the number is six. Then select those six lines to be filtered
through sort; press 6!!sort and the Return key. The six lines will be passed through
sort, and sort's output replaces the original six lines.

The filter command can only be used on complete lines, not on characters or words.

Some other filter commands (here, < CR > means press Return):

 !/the < CR > sort < CR > : Sort from the current line up to and including the
next line containing the
 !1Ggrep the < CR > : Replace from the current line to and including Line 1
with just the lines that contain the
 !Gawk '{print $1}' < CR > : From the current line to the end of file, replace
every line with just its first word.

10.7 Marking Lines and Characters


You can mark lines and characters to be used as targest for movement, deletion,
change, yanking, and filtering using the command mc, where c is a lowercase letter.
For example, put the cursor in the middle of some word and press ma. This marks the
character under the cursor as mark a.

Now, move the cursor off the marked character and to a different line ( use the cursor
keys, CTRL-u, or whatever). To return to the marked line, press 'a (that is, single
quote, then a). This moves to the first non-white space character on the line containing
mark a.

Move off that line again. To return to the marked character, press `a (that is,
backquote, then a). This moves on top of the character marked with a.

Marking is usually used with deleting, changing, yanking or filtering. For example,
move the cursor to a line other than the one containing mark a, and then press d'a (d,
single quote, a). This deletes from the current line to and including the line marked
with a.

Put the cursor in the middle of a different word and press mb to set mark b. Now,
move the cursor away from that word (but only a few lines, so you can see what we're
about to do more easily), and then press d`b (d, backquote, b). This deletes from the
current CHARACTER to and including the CHARACTER marked with b.

As another example, to sort the output of who, mark the first line (ma), then move the
cursor to the last line and press !'asort and the Return key.

If you jump to a mark and decide you want to jump back to whatever you jumped
from, you can press '' (jump back to line) or `` (jump back to character).

10.8 Naming Buffers


When you delete, change, or yank text, the original text is stored (until the next delete,
change, or yank) in an unnamed buffer from which it can be put using p or P. Using
the unnamed buffer, only the most recently deleted, changed or yanked text may be
recovered.

If you wish to delete, change, or yank multiple sections of text and remember them all
(up to a maximum of 26), you can give a buffer name ahead of the delete change or
yank command. A buffer name has the form "c (double quote, lowercase c).

For example, press "ayy to yank the current line into buffer a, then move to a different
line and press "byy to yank that line into buffer b. Now, move elsewhere in the file
and press "ap and "bp to put copies of the text stored in buffers a and b.
Some other named buffer commands:

 "a6yy : Yank six lines (current and next five) into buffer a
 "bd1G : Delete from the curernt line to and including Line 1, storing the
deleted lines in buffer b
 "cy'c : Yank from the current line to the line marked c into buffer c (marks and
buffers are distinct, and may have the same name without confusing vi)

10.9 Substitutions
To substitute one chunk of text for another in lines throughout your file, use the :s
command. Some substitute examples:

 :1,$s/the/THE/g From Line 1 to the last line (line $), substitute for the text
THE; do this globally in each line where the occurrs
 :'a,.s/.*/ha ha/ From the line marked a to the current line (line .), substitute for
everything on the line the text ha ha

10.10 Miscellaneous "Colon Commands"


All colon commands begin with a colon; when you press the colon, the cursor drops to
the lower left corner of the screen, and a colon prompt is displayed waiting for you to
finish your colon command.

Some important examples:

 :w Write the buffer contents to the file without quitting from vi


 :w abc Write the buffer contents to the file abc (creating abc if it doesn't exist,
or overwriting current contents if it does exist) without quitting from vi
 :1,10w abc Write lines 1 through 10 to file abc
 :'a,$w abc Write from the line marked a to the last line into file abc
 :e abc Edit file abc, instead of the current file. vi prints an error message if
changes have been made to the curernt file that have not been saved with :w
 :e! abc Edit file abc, throwing away any changes that may have been made to
the current file
 :e # Edit the prior file edited (successive :e# commands toggle back and forth
between two files)
 :f abc Change the file anme for the current vi buffer to abc
 :q Quit, unless unsaved chanegs have been made
 :q! Quit, throwing away any changes that may have been made
 :r abc Read the file abc into current vi buffer, after the line the cursor is on (try
:r croc to read in a copy of the croc file)
 :!cmd Execute command cmd (who, sort, ls, etc.)

10.11 Setting Options


Various options affect the "feel" of vi. You can display all the various options that can
be set using the colon command :set all. You can also use set to change options.

For example, if you want to see line numbers for the lines in the file you're editing,
use the command :set number. To turn off line numbering, use the command :set
nonumber. Most options can be abbreviated; :set nu turns on line numbering and :set
nonu turns off line numbering.

If you :set nomagic, the special meanings of regular expression characters (period,
asterisk, square bracket, etc.) are switched off. Use :set magic to restore the special
meanings.

Some options take a value. For example, :set tabstop=4 causes tabs to be displayed as
four space characters, rather than the usual eight.

If you find you always want certain options set certain ways, you can put the set
commands you want ina file .exrc, or you can set up the environment variable
EXINIT to specify the options you want.

For example, if your login shell is Bourne shell, this line could go in your .profile file:

EXINIT='set nomagic nu tabstop=4'; export EXINIT

If your login shell is a C shell, this line could go in your .login file:
setenv EXINIT 'set nomagic nu tabstop=4'

10.12 Key Mappings


If you find you're performing a series of simple commands over and over, you can
map the command series to an unused command key using the :map command. If
your mapping must include control characters such as Return key (CTRL-M in
ASCII) or the ESC (CTRL-[ in ASCII) key, precede such characters with CTRL-v to
suppress their usual special meaning.
For example, this command maps CTRL-A to move the cursor forward 55 lines, then
back up to the most recent blank line, then change that blank line to a formfeed
(CTRL-L) and three blank lines. That is, each CTRL-A will paginate the next page,
without splitting paragraphs across pages.

Note: In this command, each control character is shown as ^C, where C is some
uppercase letter. For example, CTRL-M is shown as ^M. Also, when you enter this
command you will not see the CTRL-v characters as shown: each CTRL-v merely
suppresses the usual special meaning of the following control character, so when you
press the sequence ^V^M, all you will see on the screen is ^M. In this command, ^M
is the Return key and ^[ is the ESC key.

:map ^A 55+?^$^V^Mcc^V^L^V^M^V^M^V^M^V^[

10.13 Editing Multiple Files


You can edit multiple files with vi by giving multiple file names as command line
arguments:

vi croc fatherw wknight

Three colon commands are used to move through the multiple files:

 :n Move to the next file in the argument list (you must save changes with :w
or vi will print an error message)
 :N Move to the previous file in the argument list (you must save changes
with :w or vi will print an error message)
 :rew Rewind and start over with the first file in the argument list

The :n, :N, and :rew commands are somewhat clumsy, but there are some important
benefits: the contents of named buffers ("a, "b, "c, etc.) are remembered across files,
so you can use :n and :rew with p and P to copy text back and forth between files.
Also, the most recent search string for the / and ? commands remembered across files,
so you can do repetitive searches in multiple files rather easily.

For example, try the following experiment: First get out of vi, then execute vi with
croc and wknight as arguments:

$ vi croc wknight
In croc, search for the

/the < CR >

Yank this line into buffer a:

"ayy

Now go to the next file (you've made no change to croc, so this will work):

:n < CR >

Search for the "next" line containing the, without retyping the search string:

Put a copy of buffer a after the current line in wknight:

"ap

Move down two lines, and yank the current line into buffer b:

jj"byy

Save the changes to wknight

:w < CR >

Now, rewind to croc

:rew < CR >

Search again, and put a copy of buffer b after the found line:

n"bp

Save the changes, and exit vi

ZZ

10.14 Final Remarks


This tutorial was intended to introduce some of the vi capabilities that you might
overlook in your system's vi manual or that might not be mentioned in the manual
(different systems have manuals of widely varying quality).

You will not be a vi expert after reading this tutorial, but you will have a good
appreciation of vi's capabilities. Only time and effort can make a vi expert. But the
efficiency and universality of vi make this effort pay off in the long run.

You may have decided you hate vi. So be it! But be aware that vi remains the standard
UNIX text editor - the one editor you can count on being available on every UNIX
system you'll use - so even if you prefer to use something else day-to-day, you'd be
well advised to know the bare minimum vi material covered in this tutorial.

11. Vim Reference Card


11.1 Vi states
Vi has 3 modes:

1. command mode - Normal and initial state; others return here (use ESC to abort
a partially typed command)
2. input mode - entered by specific commands a i A I o O c C s S R and ended
by ESC or abnormally with interrupt
3. line mode - i.e. waiting for input after a : , / , ? or a ! command (end with CR,
abort with CTRL-c). CTRL is the control key: CTRL-c means "control c"

11.2 Shell Commands


1. TERM= code Puts a code name for your terminal into the variable TERM
2. export TERM Conveys the value of TERM (the terminal code) to any UNIX
system program that is terminal dependant.
3. tput init Initializes the terminal so that it will function properly with various
UNIX system programs.
4. vi filename Accesses the vi screen editor so that you can edit a specified file.
5. vi file1 file2 file3 Enters three files into the vi buffer to be edited. Those files
are file1, file2, and file3.
6. view file Invoke vi editor on file in read-only mode
7. vi -R file Invoke vi editor on file in read-only mode
8. vi -r file Recover file and recent edits after system crash
9. vi -r file Recover file and recent edits after system crash

11.3 Setting Options


1. :set option Activate option
2. :set option=value Assign value to option
3. :set no option Deactivate option
4. :set Display options set by user
5. :set all Display list of all current options, both default and those set by the user
6. :set option? Display values of option

11.4 Notations used


Notations:

1. CTRL-c CTRL is the control key: CTRL-c means "control c"


2. CR is Carriage return (ENTER key)

11.5 Interrupting, cancelling


 ESC end insert or incomplete command
 CTRL-? CTRL is the control key: CTRL-? means "control ?" delete or rubout
interrupts
 CTRL-l reprint/refresh screen if CTRL-? scrambles it

11.6 File Manipulation


 ZZ Save the file and exit vi
 :wq Save the file and exit vi
 :w Write the current file
 :w! Force write the current file, if file is read-only
 :wname Write to file name
 :q Exit from vi
 :q! Force exit from vi (discarding changes)
 :e name Edit file name
 :e! reedit, discard changes
 :e + name edit file name, starting at end
 :e + n edit starting at line n
 :e # edit alternate file
 :n edit next file in arglist
 :args list files in current filelist
 :rew rewind current filelist and edit first file
 :n args specify new arglist
 :f show current file and line
 CTRL-G synonym for :f , show current file and line
 :ta tag to tag file entry tag
 CTRL-] :ta, following word is tag

11.7 Movement
 Arrows Move the cursor
 CTRL-d Scroll half page down
 CTRL-u Scroll half page up
 CTRL-f Scroll a full page down
 CTRL-b Scroll a full page up
 :0 Move to start of file
 :n Move to line number n
 :$ Move to end of file
 0 Move to start of line
 ^ Move to first non-blank character
 $ Move to end of line
 CR Move to the start of next line
 - Move to the start of previous line
 % Find matching bracket
 G goto line (last line default)
 ]] next section/function
 [[ previous section/function

11.8 Line Positioning


 H Home window line
 L Last window line
 M Middle window line
 + Next line, at first non-white
 - Previous line, at first non-white
 CR return, same as +
 j next line, same column
 k previous line, same column

11.9 Character positioning


 0 beginning of line
 $ end of line
 h forward
 l backwards
 SPACE same as l
 fx find x forward
 Fx find x backward
 ; repeat last f F
 , inverse of ;
 | to specified column
 % find matching { or }

11.10 Words, sentences, paragraphs


 w Word forward
 b Word backward
 e End of word
 ) To next sentence
 ( Back sentence
 } To next paragraph
 { Back paragraph
 W Blank delimited word
 B Back W
 E To end of W

11.11 Marking and returning


 `` (press twice the back-quote ` key) Previous context
 '' (press twice the single-quote ` key) Previous context at first non-white in line
 mx mark position with letter x
 `x (back quote key and letter x) goto mark x
 'x goto mark x at first non-white in line

11.12 Corrections during insert


 CTRL-h Erase last character
 CTRL-w Erase last word
 erase Press DELETE key, same as CTRL-h
 kill Your kill key, erase input this line
 \ Escapes CTRL-h, DELETE and kill
 ESC Ends insertion, back to command
 CTRL-? Interrupt, terminates insert
 CTRL-d Backtab over autoindent
 CTRL-v Quote non-printing character

11.13 Adjusting the screen


 CTRL-l Clear and redraw
 CTRL-r retype, eliminate @lines
 z-CR redraw, current line at window top
 z- redraw, current line at window bottom
 z. redraw, current line at window center
 /pat/z- pat line bottom
 tn Use n line window
 CTRL-e Scroll window down 1 line
 CTRL-y Scroll window up 1 line

11.14 Delete
 x Delete the character under the cursor
 X Delete the charater before the cursor
 D Delete to the end of line
 d^ Delete back to start of line
 dd Delete the current line
 ndd Delete n lines starting with the current one
 dnw Delete n words starting from cursor

11.15 Insert, change


 i Enter input mode inserting before the cursor
 I Enter input mode inserting before the first non-blank character
 a Enter input mode inserting after the cursor
 A Enter input mode inserting after the end of the line
 o Open a new line below current line and enter input mode
 O Open a new line above current line and enter input mode
 r Replace the character under the cursor (does NOT enter input mode)
 R Enter input mode replacing characters
 C shift-c. Change rest of line
 D shift-d. Delete rest of line
 s Substitute chars
 S Substitute lines
 J Join lines
 J Join lines
11.16 Copy and Paste
The "yank buffer" is filled by EVERY delete command, or explicitely by Y and yy.

 Y Copy the current line to the yank buffer


 nyy Copy n lines starting from the current to the yank buffer
 p Paste the yank buffer after the cursor (or below the current line)
 P Paste the yank buffer before the cursor (or above the current line)
 "xp Put from buffer x
 "xy Yank to buffer x
 "xd Delete into buffer x

11.17 Operators (use double to affect lines)


 d delete
 c change
 < left shift
 > right shift
 ! filter through command
 = indent for LISP
 y yank text to buffer

11.18 Search and replace


 /text Search forward for text
 ?text Search backward for text
 n Repeat the last search in the same direction
 N Repeat the last search in the reverse direction
 / Repeat the last search forward
 ? Repeat the last search backward
 [ addr ] s/from/to/ [ g ] Search for the occurence of from and replace it
with to in the current line, or in the range addr (two line numbers seperated by
command; 1,$ is the whole file). Replaces one occurrence per line, or all
occurrences if g is specified. For example, :3,20s/someword/anotherword/g
Will replace "someword" with "anotherword" starting from line 3 to line 20. 'g'
is global means replace all occurrences of "someword".

11.19 General
 :sh Forks a shell (to be exited with CTRL-d)
 :!command Forks a shell to execute command
 :set number Switch on line numbering
 :set nonumber Switch off line numbering

11.20 Line Editor Commands


 : Tells vi that the next commands you issue will be line editor commands.
 :sh Temporarily returns to the shell to perform some shell commands without
leaving vi.
 CTRL-d Escapes the temporary return to the shell and returns to vi so you can
edit the current window.
 :n Goes to the nth line of the buffer.
 :x,zw filename Writes lines from the numbers x through the number z into a
new file called filename.
 :$ Moves the cursor to the beginning of the last line in the buffer.
 :.,$d Deletes all the lines from the current line to the last line
 :r filename Inserts the contents of the file filename under the current line of the
buffer.
 :s/text/new_text/ Replaces the first instance of text on the current line
with new_text
 :s/text/new_text/g Replaces the every occurrence of text on the current line
with new_text
 :g/text/s//new_text/g Changes every occurrence of text on the buffer
to new_text.

11.21 Other commands


 u Undo the last change
 U Restore the current line
 ~ Change case
 J Join the currentline with the next line
 . Repeat last text changing command
 CTRL-g Show file name and line number

12. Related URLs


Related VIM URLs are at -

 C and C++ Beautifer http://www.metalab.unc.edu/LDP/HOWTO/C-C+


+Beautifier-HOWTO.html
 Linux goodies main site is at http://www.aldev.8m.com Mirror sites are at
- http://aldev0.webjump.com, angelfire, geocities, virtualave, 50megs, theglob
e,NBCi, Terrashare, Fortunecity, Freewebsites, Tripod, Spree, Escalix, Httpcity,
Freeservers.

13. Other Formats of this Document


This document is published in 14 different formats namely - DVI, Postscript, Latex,
Adobe Acrobat PDF, LyX, GNU-info, HTML, RTF(Rich Text Format), Plain-text,
Unix man pages, single HTML file, SGML (Linuxdoc format), SGML (Docbook
format), MS WinHelp format.

This howto document is located at -

 http://www.linuxdoc.org and click on HOWTOs and search for howto


document name using CTRL+f or ALT+f within the web-browser.

You can also find this document at the following mirrors sites -

 http://www.caldera.com/LDP/HOWTO
 http://www.linux.ucla.edu/LDP
 http://www.cc.gatech.edu/linux/LDP
 http://www.redhat.com/mirrors/LDP
 Other mirror sites near you (network-address-wise) can be found
at http://www.linuxdoc.org/mirrors.html select a site and go to directory
/LDP/HOWTO/xxxxx-HOWTO.html

 You can get this HOWTO document as a single file tar ball in HTML, DVI,
Postscript or SGML formats from
-ftp://www.linuxdoc.org/pub/Linux/docs/HOWTO/other-formats/ and http://
www.linuxdoc.org/docs.html#howto
 Plain text format is
in: ftp://www.linuxdoc.org/pub/Linux/docs/HOWTO and http://www.linuxdoc
.org/docs.html#howto
 Single HTML file format is in: http://www.linuxdoc.org/docs.html#howto

Single HTML file can be created with command (see man sgml2html) -
sgml2html -split 0 xxxxhowto.sgml
 Translations to other languages like French, German, Spanish, Chinese,
Japanese are
in ftp://www.linuxdoc.org/pub/Linux/docs/HOWTO andhttp://www.linuxdoc.
org/docs.html#howto Any help from you to translate to other languages is
welcome.

The document is written using a tool called "SGML-Tools" which can be got from
- http://www.sgmltools.org Compiling the source you will get the following
commands like

 sgml2html xxxxhowto.sgml (to generate html file)


 sgml2html -split 0 xxxxhowto.sgml (to generate a single page html file)
 sgml2rtf xxxxhowto.sgml (to generate RTF file)
 sgml2latex xxxxhowto.sgml (to generate latex file)

13.1 Acrobat PDF format


PDF file can be generated from postscript file using either
acrobat distill or Ghostscript. And postscript file is generated from DVI which in
turn is generated from LaTex file. You can download distill software
from http://www.adobe.com. Given below is a sample session:

bash$ man sgml2latex


bash$ sgml2latex filename.sgml
bash$ man dvips
bash$ dvips -o filename.ps filename.dvi
bash$ distill filename.ps
bash$ man ghostscript
bash$ man ps2pdf
bash$ ps2pdf input.ps output.pdf
bash$ acroread output.pdf &

Or you can use Ghostscript command ps2pdf. ps2pdf is a work-alike for nearly all the
functionality of Adobe's Acrobat Distiller product: it converts PostScript files to
Portable Document Format (PDF) files. ps2pdf is implemented as a very small
command script (batch file) that invokes Ghostscript, selecting a special "output
device" called pdfwrite. In order to use ps2pdf, the pdfwrite device must be included
in the makefile when Ghostscript was compiled; see the documentation on building
Ghostscript for details.
13.2 Convert Linuxdoc to Docbook format
This document is written in linuxdoc SGML format. The Docbook SGML format
supercedes the linuxdoc format and has lot more features than linuxdoc. The linuxdoc
is very simple and is easy to use. To convert linuxdoc SGML file to Docbook SGML
use the program ld2db.sh and some perl scripts. The ld2db output is not 100% clean
and you need to use the clean_ld2db.pl perl script. You may need to manually correct
few lines in the document.

 Download ld2db program


from http://www.dcs.gla.ac.uk/~rrt/docbook.html or from Al Dev site
 Download the cleanup_ld2db.pl perl script from from Al Dev site

The ld2db.sh is not 100% clean, you will get lots of errors when you run

bash$ ld2db.sh file-linuxdoc.sgml db.sgml


bash$ cleanup.pl db.sgml > db_clean.sgml
bash$ gvim db_clean.sgml
bash$ docbook2html db.sgml

And you may have to manually edit some of the minor errors after running the perl
script. For e.g. you may need to put closing tag < /Para> for each < Listitem>

13.3 Convert to MS WinHelp format


You can convert the SGML howto document to Microsoft Windows Help file, first
convert the sgml to html using:

bash$ sgml2html xxxxhowto.sgml (to generate html file)


bash$ sgml2html -split 0 xxxxhowto.sgml (to generate a single page
html file)

Then use the tool HtmlToHlp. You can also use sgml2rtf and then use the RTF files for
generating winhelp files.

13.4 Reading various formats


In order to view the document in dvi format, use the xdvi program. The xdvi program
is located in tetex-xdvi*.rpm package in Redhat Linux which can be located through
ControlPanel | Applications | Publishing | TeX menu buttons. To read dvi document
give the command -
xdvi -geometry 80x90 howto.dvi
man xdvi
And resize the window with mouse. To navigate use Arrow keys, Page Up, Page
Down keys, also you can use 'f', 'd', 'u', 'c', 'l', 'r', 'p', 'n' letter keys to move up, down,
center, next page, previous page etc. To turn off expert menu press 'x'.

You can read postscript file using the program 'gv' (ghostview) or 'ghostscript'. The
ghostscript program is in ghostscript*.rpm package and gv program is in gv*.rpm
package in Redhat Linux which can be located through ControlPanel | Applications |
Graphics menu buttons. The gv program is much more user friendly than ghostscript.
Also ghostscript and gv are available on other platforms like OS/2, Windows 95 and
NT, you view this document even on those platforms.

 Get ghostscript for Windows 95, OS/2, and for all OSes
from http://www.cs.wisc.edu/~ghost

To read postscript document give the command -


gv howto.ps
ghostscript howto.ps

You can read HTML format document using Netscape Navigator, Microsoft Internet
explorer, Redhat Baron Web browser or any of the 10 other web browsers.

You can read the latex, LyX output using LyX a X-Windows front end to latex.

14. Copyright Notice


Copyright policy is GNU/GPL as per LDP (Linux Documentation project). LDP is a
GNU/GPL project. Additional restrictions are - you must retain the author's name,
email address and this copyright notice on all the copies. If you make any changes or
additions to this document then you should notify all the authors of this document.

Vim Color Editor HOW-TO (Vi Improved


with syntax color highlighting)
Al Dev (Alavoor Vasudevan) [email protected]
v17.2, 28 June 2001

This document is a guide to quickly setting up the Vim color editor on Linux or Unix
systems. The information here will improve the productivity of programmers because
the Vim editor supports syntax color highlighting and bold fonts, improving the
"readability" of program code. A programmer's productivity improves 2 to 3 times
with a color editor like Vim. The information in this document applies to all operating
sytems where Vim works, such as Linux, Windows 95/NT, Apple Mac, IBM OSes, VMS,
BeOS and all flavors of Unix like Solaris, HPUX, AIX, SCO, Sinix, BSD, Ultrix etc.. (it
means almost all operating systems on this planet!)

1. Introduction
 1.1 Before you Install
 1.2 Install Vim on Redhat Linux
 1.3 Install Vim on GNU Debian Linux
 1.4 Install Vim on Unixes
 1.5 Install Vim on Microsoft Windows 95/NT
 1.6 Install Vim on VMS
 1.7 Install Vim on OS/2
 1.8 Install Vim on Apple Macintosh

2. Install Vim on Microsoft Windows 95/NT


 2.1 Install bash shell
 2.2 Edit bash_profile
 2.3 Setup Window colors

3. Setup gvim init files


 3.1 Sample gvimrc file
 3.2 Xdefaults parameters
4. Color Syntax init files
 4.1 Auto source-in method
 4.2 Manual method

5. VIM Usage
6. Vi companions
 6.1 Ctags for ESQL
 6.2 Ctags for JavaScript programs, Korn, Bourne shells
 6.3 Debugger gdb

7. Online VIM help


8. Vim Home page and Vim links
9. Vim Tutorial
 9.1 Vim Hands-on Tutorial
 9.2 Vi Tutorials on Internet

10. Vi Tutorial
 10.1 Cursor Movement Commands
 10.2 Repeat Counts
 10.3 Deleting Text
 10.4 Changing Text
 10.5 Yanking (Copying) Text
 10.6 Filtering text
 10.7 Marking Lines and Characters
 10.8 Naming Buffers
 10.9 Substitutions
 10.10 Miscellaneous "Colon Commands"
 10.11 Setting Options
 10.12 Key Mappings
 10.13 Editing Multiple Files
 10.14 Final Remarks
11. Vim Reference Card
 11.1 Vi states
 11.2 Shell Commands
 11.3 Setting Options
 11.4 Notations used
 11.5 Interrupting, cancelling
 11.6 File Manipulation
 11.7 Movement
 11.8 Line Positioning
 11.9 Character positioning
 11.10 Words, sentences, paragraphs
 11.11 Marking and returning
 11.12 Corrections during insert
 11.13 Adjusting the screen
 11.14 Delete
 11.15 Insert, change
 11.16 Copy and Paste
 11.17 Operators (use double to affect lines)
 11.18 Search and replace
 11.19 General
 11.20 Line Editor Commands
 11.21 Other commands

12. Related URLs


13. Other Formats of this Document
 13.1 Acrobat PDF format
 13.2 Convert Linuxdoc to Docbook format
 13.3 Convert to MS WinHelp format
 13.4 Reading various formats

14. Copyright Notice

C++ Programming HOW-TO


Al Dev (Alavoor Vasudevan) [email protected]
v40.3, 26 July 2001

This document provides a comprehensive list of C++ URL pointers, links to C++ online
textbooks, and programming tips on C++. This document also provides a C++ library
which imitates Java-language, and which has various methods to avoid memory
problems in C++. Using this library you can compile Java's source code under C++. This
document serves as a "Home of C++ language". The information given here will help
you to program properly in C++ language and applies to all the operating systems
that is - Linux, MS DOS, BeOS, Apple Macintosh OS, Microsoft Windows
95/98/NT/2000, OS/2, IBM OSes (MVS, AS/400 etc..), VAX VMS, Novell Netware, all
flavors of Unix like Solaris, HPUX, AIX, SCO, Sinix, BSD, etc.. and to all other operating
systems which support "C++" compiler (it means almost all the operating systems on
this planet).

1. Introduction
 1.1 C++ v/s Java
 1.2 Which one Ada95, "C", "C++" or Java ??
 1.3 Problems facing the current C++ compilers
 1.4 COOP - C++ Object Oriented Programming-language

2. String Class Varieties


 2.1 Multiple Inheritance - Sample Custom String class

3. Best C++ compilers for MS Windows


2000/NT/95/98/ME/XP
4. Download String
5. How Can I trust Al Dev's String Class ??
6. Usage of String class
 6.1 Operators
 6.2 Functions

7. String.h file
 7.1 StringBuffer.h
 7.2 StringTokenizer.h

8. Renaming the String class


 8.1 Case 1: Simple rename
 8.2 Case 2: Resolve conflict

9. File Class
10. C++ Zap (Delete) function
11. Pointers are problems
12. Usage of my_malloc and my_free
 12.1 Garbage Collector for C++

13. Debug files


14. Java like API
15. IDE tools for C++
16. C++ Online Textbooks and Docs
17. C++ Coding Standards
18. C++ Online Docs
 18.1 C++ Tutorials
 18.2 Useful links
 18.3 C++ Quick-Reference
 18.4 C++ Usenet Newsgroups

19. Memory Tools


20. Related URLs
21. C++ Scripting Languages
 21.1 PIKE (C/C++ Scripting Language)
 21.2 SoftIntegration Ch (C/C++ Scripting Language)
 21.3 PHP (C++ Scripting Language)

22. Templates
23. STL References
 23.1 Overview of the STL
 23.2 Header Files
 23.3 The Container Classes Interface
 23.4 Vectors
 23.5 Iterators and the STL
 23.6 Lists
 23.7 Sets
 23.8 Maps
 23.9 STL Algorithms

24. Threads in C++


 24.1 Threads Tutorial
 24.2 Designing a Thread Class in C++

25. C++ Utilities


26. Other Formats of this Document
 26.1 Acrobat PDF format
 26.2 Convert Linuxdoc to Docbook format
 26.3 Convert to MS WinHelp format
 26.4 Reading various formats
27. Translations To Other Languages
28. Copyright
29. Appendix A String Program Files
1. Introduction
The purpose of this document is to provide you with a comprehensive list of URL
pointers and programming tips on C++. Also, this document provides a C++ library
having Java-like String class, string tokenizer, memory functions and many other
functions, which can be used in general C++ applications. Also various examples are
given here which demonstrate the usage of this library.

This document is not a textbook on C++, and there are already several excellent "on-
line Text books" on internet. If you are new to C++ and you never programmed in C+
+, then it is strongly suggested that you first read the online C++ Textbooks given in
the chapter C++ Online Textbooks and then follow the subsequent chapters. It is
suggested that you purchase a textbook on C++ for reference from online bookstores
like amazon or barnes.

1.1 C++ v/s Java


C++ is one of the most powerful language and will be used for a long time in the
future inspite of emergence of Java. C++ runs extremely fast and is in fact10 to 20
times FASTER than Java. Java runs very slow because it is a byte-code-interpreted
language running on top of "virtual machine". Java runs faster with JIT (Just-In-Time)
compiler, but it is still slower than C++. And optimized C++ program is about 3 to 4
times faster than Java (with JIT compiler). Then, why do people use Java? Because it
is pure object oriented and is easier to program in Java, as Java automates memory
management, and programmers do not directly deal with memory allocations. This
document attempts to automate the memory management in C++ to make it much
more easy to use. The library given here will make C++ look like Java and will enable
"C++" to compete with Java language.

Because of manual memory allocations, debugging the C++ programs consumes a


major portion of time. This document will give you some better ideas and tips to
reduce the debugging time.

1.2 Which one Ada95, "C", "C++" or Java ??


Language choice is very difficult. There are too many parameters - people, people
skills, cost, tools, politics (even national politics) and influence of
businessmen/commercial companies. The best language based on technical merits
does not get selected simply due to political decisions!

Java is much closer to Ada95 than C++. Java is derived from Ada95. Ada95 gets the
maximum points as per David Wheeler's Ada comparison chart. Ada got 93%, Java
72%, C++ 68% and C got 53%. C++ and Java are closer in points(only 4%
difference), hence Java is not a very big revolution as compared to C++. On other
hand, Ada is a very big revolution and improvement over C++. The scores are like 4
students taking exams and student with highest score is Ada (93%). Who knows?
Perhaps in future Ada95 will replace Java!! Development costs of Ada is half of C++
as per Stephen F. Zeigler. Ada95 is available at -

 Ada home http://www.gnuada.org.


 Google Ada index

Since C++ programmers are abundant, it is recommended you do programming in


object-oriented "C++" for all your application programming or general purpose
programming. You can take full advantage of object oriented facilities of C++. The
C++ compiler is lot more complex than "C" compiler and C++ programs may run bit
slower than "C" programs. But speed difference between "C" and "C++" is very
minute - it could be few milli-seconds which may have little impact for real-time
programming. Since computer hardware is becoming cheaper and faster and memory
'RAM' is getting faster and cheaper, it is worth doing code in C++ rather than "C" as
time saved in clarity and re-usability of C++ code offsets the slow speed. Compiler
optimizer options like -O or -O3 can speed up C++/C which is not available in Java.

Nowadays, "C" language is primarily used for "systems programming" to develop


operating systems, device drivers etc..

Note: Using the String, StringBuffer, StringTokenizer and StringReader classes


given in this howto, you can code in C++ which "exactly" looks like Java. This
document tries to close the gap between C++ and Java, by imitating Java classes in
C++

Java is platform independent language more suitable for developing GUI running
inside web-browsers (Java applets) but runs very slow. Prefer to use web-server-side
programming "Fast-CGI" with C++ and HTML, DHTML, XML to get better
performance. Hence, the golden rule is "Web-server side programming use C++ and
web-client side (browser) programming use Java applets". The reason is - the server-
side OS (Linux) is under your control and never changes, but you will never know
what the client side web-browser OS is. It can be Internet appliance device (embedded
linux+netscape) or computers running Windows 95/98/NT/2000 or Linux, Apple
Mac, OS/2, Netware, Solaris etc..

The advantage of Java language is that you can create "Applets (GUI)" which can run
on any client OS platform. Java was created to replace the Microsoft Windows 95/NT
GUI APIs like MS Visual Basic or MS Visual C++. In other words - "Java is the
cross-platform Windows-GUI API language of next century". Many web-browsers
like Netscape supports Java applets and web-browser like Hot Java is written in java
itself. But the price you pay for cross-platform portability is the performance,
applications written in Java run very slow.

Hence, Java runs on "client" and C++ runs on servers.

1.3 Problems facing the current C++ compilers


Since C++ is super-set of C, it got all the bad features of "C" language. Manual
allocation and deallocation of memory is tedious and error prone (seeGarbage
Collector for C++).

In "C" programming - memory leaks, memory overflows are very common due to
usage of features like -

Datatype char * and char[]


String functions like strcpy, strcat, strncpy, strncat, etc..
Memory functions like malloc, realloc, strdup, etc..

The usage of char * and strcpy causes horrible memory problems due
to "overflow", "fence past errors", "memory corruption", "step-on-others-toe"(hurting
other variable's memory locations) or "memory leaks". The memory problems are
extremely hard to debug and are very time consuming to fix and trouble-shoot.
Memory problems bring down the productivity of programmers. This document helps
in increasing the productivity of programmers via different methods addressed to
solve the memory defects in "C++". Memory related bugs are very tough to crack, and
even experienced programmers take several days or weeks to debug memory related
problems. Memory bugs may be hide inside the code for several months and can
cause unexpected program crashes. The memory bugs due to usage of char
* and pointers in C/C++ is costing $2 billion every year in time lost due to debugging
and downtime of programs. If you use char * and pointers in C++ then it is a very
costly affair, especially if your program size is greater than 10,000 lines of code.
Hence, the following techniques are proposed to overcome the faults of "C" language.
Give preference in the following order -

1. Use references instead of pointers.


2. Java style String class (given in this howto) or STDLib string class.
3. Character pointers (char *) in C++ limit the usage of char * to cases where you
cannot use the String class.
4. Character pointers (char *) in C using extern linkage specification, if you do not
want to use (char *) in C++.

To use "C char *", you would put all your "C" programs in a separate file and link to
"C++" programs using the linkage-specification statement extern "C" -

extern "C" {
#include <stdlib.h>
}

extern "C" {
comp();
some_c_function();
}

The extern "C" is a linkage specification and is a flag that everything within the
enclosing block (brace-surrounded) uses C linkage, not C++ linkage.

The 'String class' utilises the constructor and destructor features to automate memory
management and provides access to functions like ltrim, substring, etc..

See also related 'string class' in the C++ compiler. The string class is part of the
standard GNU C++ library and provides many string manipulation functions. Because
the C++ 'string class' and 'String class' library provides many string manipulation
functions, there is less need to use the character pointer approach to write your own
string functions. Also, C++ programmers must be encouraged to use 'new', 'delete'
operators instead of using 'malloc' or 'free'.

The 'String class' does everything that char * or char [] does. It can completely
replace char datatype. Plus added benefit is that programmers do not have to worry
about the memory problems and memory allocation at all.

1.4 COOP - C++ Object Oriented Programming-language


A problem with C++ is that it is a superset of C, and, although programmers can use
the good (object oriented) features of C++ and avoid the bad features of C, there is
nothing to force them to do so. So, many C++ programs are written with no object
oriented features and continue to use the bad features of C that the use of C++ should
have overcome.

Therefore, I propose that we create a new version of C++ that does not allow the use
of the bad features of C.

I propose that this new version of C++ be called COOP (say koop), which is an
acronym for C++ Object Oriented Programming-language" . COOP should be
pronounced like chicken coop. (The logo of COOP language is a big fat Hen inside
coop!) I propose that the file extension for COOP files be .coo, which will not conflict
with .c for C programs or .cpp for C++ programs.

To begin with, write the COOP as a front end to C++. That is COOP pre-processes the
code syntax and then uses the standard C++ compiler to compile the program. COOP
acts as a front end to C++ compiler. (To start with, COOP will be a very good
project/thesis topic for university students)

The following are some other proposed features of COOP:

 COOP will borrow some best ideas from Microsoft C#, Microsoft put lot of
efforts, and you can simply utilize them. Specs are at csharp-specs and seeC#
overview.
 Is a subset of C++ language but will force programmer to use obejct oriented
programming.
 Pure Object-oriented langauge but retains syntax of C++.
 Remove all bad or confusing features of C++ in COOP, for e.g. multiple-
inheritance, operator overloading, limit usage of pointers, etc...
 Prevent writing "C" like programming in COOP, something which C++ currently
allows. Delete all C features which are considered bad or
redundant/duplicates, like printf, fprintf, malloc, struct, free etc..
 No downward compatibility to "C" language.
 Code written in COOP will be easy to maintain and is easily
understandable/readable.
 Code written in "COOP" will be re-usable (thru components, modules,
objects). Supports re-usable software components, thereby facilitating Rapid
Application Development.
 COOP is simple, robust, OOP, has bare mininum syntax (avoiding confusing,
redundant, extra constructs of C++ for e.g remove struct and use class)
Also borrow ideas from -

 Java - Sun Microsystem put lot of effort, and you can simply utilize that.
 Connective C++ at http://www.quintessent.com/products/cc++.

2. String Class Varieties


The string class is the most vital object in programming, and string manipulations are
most extensively used and they comprise of 20 to 60% of total code. There are 3
variety of string classes. Ofcourse, you can build your own string class by simply
inheriting from these string classes -

 String class given in this document Appendix A String.h


 GNU string class
o GNU C++ Library - Univ of Tech,
Sydney http://www.socs.uts.edu.au/doc/gnuinfo/libg++/libg++_18.html
and user's guide
o mirror site Gesellschaft http://www-aix.gsi.de/doc/gnu/libg+
+_18.html#SEC23 and user's guide
o mirror site Techno,
Russia http://www.techno.spb.ru/~xbatob/FAQ/GNU/libg+
+_19.html#SEC27 and user's guide
o mirror site Univ of Utah http://www.math.utah.edu/docs/info/libg+
+_19.html#SEC27 and user's guide
 Qt String class at http://doc.trolltech.com/qstring.html mirror
at http://www.cs.berkeley.edu/~dmartin/qt/qstring.html
 If none of these alternatives are suitable, you can build your own string class.
You can start with one or more of the pre-built classes listed above (by using
single or multiple inheritance.)

2.1 Multiple Inheritance - Sample Custom String class


As mentioned above, you can build your own custom string class from the pre-built
classes by single or multiple inheritance. In this section we will build a sample custom
string class by using multiple inheritance, inheriting from the GNU string class and
the string class presented in Appendix H.

Start by downloading the sample file 'string_multi.h' from Appendix A . That file is
reproduced below:
// ******************************************************************
// Sample program to demonstrate constructing your own string class
// by deriving from the String class and stdlib's "string" class
// ******************************************************************

#ifndef __STRING_MULTI_H_
#define __STRING_MULTI_H_

#include <string>
#include "String.h"

// Important Notes: In C++ the constructors, destructors and copy


// operator are NOT inherited by the derived classes!!
// Hence, if the operators like =, + etc.. are defined in
// base class and those operators use the base class's contructors
// then you MUST define equivalent constructors in the derived
// class. See the sample given below where constructors mystring(),
// mystring(char[]) are defined.
//
// Also when you use operator as in atmpstr + mstr, what you are really
// calling is atmpstr.operator+(mstr). The atmpstr is declared a
mystring

class mystring:public String, string


{
public:
mystring():String() {} // These are needed for operator=, +
mystring(char bb[]):String(bb) {} // These are needed for
operator=, +
mystring(char bb[], int start, int slength):String(bb, start,
slength) {}
mystring(int bb):String(bb) {} // needed by operator+
mystring(unsigned long bb):String(bb) {} // needed by
operator+
mystring(long bb):String(bb) {} // needed by operator+
mystring(float bb):String(bb) {} // needed by operator+
mystring(double bb):String(bb) {} // needed by operator+
mystring(const String & rhs):String(rhs) {} // Copy
Constructor needed by operator+
mystring(StringBuffer sb):String(sb) {} // Java compatibility
mystring(int bb, bool dummy):String(bb, dummy) {} // for
StringBuffer class

int mystraa; // customizations of mystring


private:
int mystrbb; // customizations of mystring
};

#endif // __STRING_MULTI_H_

3. Best C++ compilers for MS Windows


2000/NT/95/98/ME/XP
Since MS Windows is quite popular for C++ development, the string class library
given in this document works well and runs very well on all the versions of MS
Windows i.e. MS Win XP/2000/NT/95/98/ME. The C++ compilers for MS Windows
are :

 GNU BloodShed at http://www.bloodshed.net/devcpp.html rated 1st (the best


among all)
 Borland C++
compiler http://www.borland.com/bcppbuilder/freecompiler rated 2nd
 Microsoft Visual C++ compiler http://msdn.microsoft.com/visualc rated 3rd
 MSDOS C++ compiler http://www.delorie.com/djgpp

The String class in this document is tested with all the above compilers. It works fine
with MS Visual C++ compiler v6.0, Borland C++ v5.2, Borland C++ compiler v5.5.1 and
Bloodshed compiler.

4. Download String
All the programs, examples are given in Appendix of this document. You can
download as a single tar zip, the String class, libraries and example programs from

 Go here and click on C++Programming howto.tar.gz


file http://www.aldev.8m.com
 Mirror sites are at
- http://aldev0.webjump.com, angelfire, geocities, virtualave, 50megs, theglob
e, NBCi, Terrashare, Fortunecity, Freewebsites, Tripod,Spree, Escalix, Httpcity,
Freeservers.

5. How Can I trust Al Dev's String Class ??


You may a have question of mis-trust on the String class software. To build
confidence, there is a scientific method to verify the functionality of Al Dev's String
class. In modern days, computer scientists use the CPU power instead of human brain
power to verify and validate the software. Human brain is too slow and hence it is
better to use the computer's power to test and validate software.

The program example_String.cpp (and also given in Appendix A ) has regression test
module which you can use to run the regression tests several millions of times
automatically. After running the regression tests on the String class you can certify
that the String class program is a ROCK SOLID and a BULLET-PROOF program.
I tested the String class with repeat cycle = 50000 and it ran and completed the
program without crash. While it is running I did not notice any memory leak. On
linux, I used /usr/bin/gtop, unix top command, KDEStart->System->KDE System
Gaurd and KDEStart->System->Process management to monitor the cpu and memory
usage.

I recommend that you start the regression test with repeat cycle equal to 10 million or
greater. The greater the repeat cycle number the greater will be your confidence!!
Start the test and go to lunch and come back to see the results!!

6. Usage of String class


To use String class, you should first refer to a sample program "example_String.cpp"
given in Appendix A and the String class which is given in Appendix A.

The 'String class' is a complete replacement for char and char * datatype. You can
use 'String class' just like char and get much more functionalities. You should link
with the library 'libString.a' which you can build from the makefile given in Appendix
A and copy the library to /usr/lib or /lib directory where all the "C++" libraries are
located. To use the 'libString.a' compile your programs like -

g++ example.cpp -lString

See illustration sample code as given below -

String aa;

aa = "Creating an Universe is very easy, similar to creating a baby


human.";

// You can use aa.val() like a 'char *' variable in programs


for (unsigned long tmpii = 0; tmpii < aa.length(); tmpii++)
{
//fprintf(stdout, "aa.val()[%ld]=%c ", tmpii, aa.val()
[tmpii]);
fprintf(stdout, "aa[%ld]=%c ", tmpii, aa[tmpii]);
}

// Using pointers on 'char *' val ...


for (char *tmpcc = aa.val(); *tmpcc != 0; tmpcc++)
{
fprintf(stdout, "aa.val()=%c ", *tmpcc);
}
6.1 Operators
The 'String class' provides these operators :-

 Equal to ==
 Not equal to !=
 Assignment =
 Add to itself and Assignment +=
 String concatenation or addition +

For example to use operators -

String aa;
String bb("Bill Clinton");

aa = "put some value string"; // assignment operator


aa += "add some more"; // Add to itself and assign operator
aa = "My name is" + " Alavoor Vasudevan "; // string cat operator

if (bb == "Bill Clinton") // boolean equal to operator


cout << "bb is equal to 'Bill Clinton' " << endl;

if (bb != "Al Gore") // boolean 'not equal' to operator


cout << "bb is not equal to 'Al Gore'" << endl;

6.2 Functions
The functions provided by String class has the same name as that of Java language's
String class. The function names and the behaviour is exactly same as that of Java's
String class. StringBuffer class is also provided. This will facilitate portability of code
between Java and C++ (you can cut and paste and do minimum changes to code). The
code from Java's function body can be copied into C++ member function body and
with very mininum changes the code will compile under C++. Another advantage is
that developers coding in both Java and C++ do not need to remember two different
syntax or function names.

For example to convert integer to string do -

String aa;
aa = 34; // The '=' operator will convert int to string
cout << "The value of aa is : " << aa.val() << endl;

aa = 234.878; // The '=' operator will convert float to string


cout << "The value of aa is : " << aa.val() << endl;

aa = 34 + 234.878;
cout << "The value of aa is : " << aa.val() << endl;
// The output aa will be '268.878'

// You must cast String to convert


aa = (String) 34 + " Can create infinite number of universes!! " +
234.878;
cout << "The value of aa is : " << aa.val() << endl;
// The output aa will be '34 Can create infinite number of universes!!
234.878'

Refer to Appendix A String.h for details about the String class function names. The
same file String.h is reproduced here in next section.

7. String.h file
In C++ (or any object oriented language), you just read the "class data-structure" (i.e.
interface) to begin using that object. You just need to understand the interface and not
the implementation of the interface. In case of String class, you just need to read and
understand the String class in String.h file. You do not need to read the entire
implementation (String.cpp) in order to use String class. The object oriented classes
are real time saver and they very neatly hide the implementation.

(In object oriented Java language there is the equivalent called 'interface' , which
hides the implementation details.)

Given below is String.h file and see also Appendix A String.h

//
// Author : Al Dev Email: [email protected]
// Use string class or String class
//
// To prevent memory leaks - a char class to manage character variables
// Always prefer to use String or string class
// instead of char[] or char *
//

#ifndef __STRING_H_ALDEV_
#define __STRING_H_ALDEV_
// do not use iostream as program becomes bulky..
#ifdef NOT_MSWINDOWS
#include <iostream>
#else
#include <iostream.h> // some compilers like .h here. Why???
#endif // NOT_MSWINDOWS

#include <stdio.h> // for FILE and sprintf()


//#include <list.h> // for list

// For MS Windows 95 VC++ or Borland C++ compiler do -


//see file d:\program files\CBuilder\include\examples\stdlib\list.cpp and
include\list.h
//#include <list> // for list
//using namespace std;

const short INITIAL_SIZE = 50;


const short NUMBER_LENGTH = 300;
const int MAX_ISTREAM_SIZE = 2048;

//class StringBuffer;

// I compiled and tested this string class on Linux (Redhat 7.1) and
// MS Windows Borland C++ version 5.2 (win32). This should also work
// using MS Visual C++ compiler
class String
{
public:
String();
String(const char bb[]); // needed by operator+
String(const char bb[], int start, int slength); // subset of
chars
String(int bb); // needed by operator+
String(unsigned long bb); // needed by operator+
String(long bb); // needed by operator+
String(float bb); // needed by operator+
String(double bb); // needed by operator+
String(const String & rhs); // Copy Constructor needed by
operator+
//String(StringBuffer sb); // Java compatibility - but causes
compile problem on MS windows and core dumps
String(int bb, bool dummy); // for StringBuffer class
virtual ~String(); // Made virtual so that when base class is
deleted
// then the derived
class destructor is called.

char *val() {return sval;} // It is not safe to make sval


public

// Functions below imitate Java language's String object


unsigned long length();
char charAt(int where);
void getChars(int sourceStart, int sourceEnd,
char target[], int targetStart);
char* toCharArray();
char* getBytes();
bool equals(String str2); // See also == operator
bool equals(char *str2); // See also == operator
bool equalsIgnoreCase(String str2);

bool regionMatches(int startIndex, String str2,


int str2StartIndex, int numChars);
bool regionMatches(bool ignoreCase, int startIndex,
String str2, int str2StartIndex, int
numChars);

String toUpperCase();
String toLowerCase();

bool startsWith(String str2);


bool startsWith(char *str2);

bool endsWith(String str2);


bool endsWith(char *str2);

int compareTo(String str2);


int compareTo(char *str2);
int compareToIgnoreCase(String str2);
int compareToIgnoreCase(char *str2);

int indexOf(char ch, int startIndex = 0);


int indexOf(char *str2, int startIndex = 0);
int indexOf(String str2, int startIndex = 0);

int lastIndexOf(char ch, int startIndex = 0);


int lastIndexOf(char *str2, int startIndex = 0);
int lastIndexOf(String str2, int startIndex = 0);

String substring(int startIndex, int endIndex = 0);


String replace(char original, char replacement);
String replace(char *original, char *replacement);

String trim(); // See also overloaded trim()

String concat(String str2); // See also operator +


String concat(char *str2); // See also operator +
String concat(int bb);
String concat(unsigned long bb);
String concat(float bb);
String concat(double bb);

String reverse(); // See also overloaded reverse()


String deleteCharAt(int loc);
String deleteStr(int startIndex, int endIndex); // Java's
"delete()"

String valueOf(char ch)


{char aa[2]; aa[0]=ch; aa[1]=0; return String(aa);}
String valueOf(char chars[]){ return String(chars);}
String valueOf(char chars[], int startIndex, int numChars);
String valueOf(bool tf)
{if (tf) return String("true"); else return
String("false");}
String valueOf(int num){ return String(num);}
String valueOf(long num){ return String(num);}
String valueOf(float num) {return String(num);}
String valueOf(double num) {return String(num);}

// See also StringBuffer class in this file given below

// ---- End of Java like String object functions -----

//////////////////////////////////////////////////////
// List of additonal functions not in java
//////////////////////////////////////////////////////
String ltrim();
void ltrim(bool dummy); // Directly changes object. dummy to
get different signature
String rtrim();
void rtrim(bool dummy); // Directly changes object. See also
chopall().
// dummy to get different signature

void chopall(char ch='\n'); // removes trailing character


'ch'. See also rtrim()
void chop(); // removes one trailing character

void roundf(float input_val, short precision);


void decompose_float(long *integral, long *fraction);

void roundd(double input_val, short precision);


void decompose_double(long *integral, long *fraction);

void explode(char *separator); // see also token() and


overloaded explode()
String *explode(int & strcount, char separator = ' '); // see
also token()
void implode(char *glue);
void join(char *glue);
String repeat(char *input, unsigned int multiplier);
String tr(char *from, char *to); // translate characters
String center(int padlength, char padchar = ' ');
String space(int number = 0, char padchar = ' ');
String xrange(char start, char end);
String compress(char *list = " ");
String left(int slength = 0, char padchar = ' ');
String right(int slength = 0, char padchar = ' ');
String overlay(char *newstr, int start = 0, int slength = 0,
char padchar = ' ');

String at(char *regx); // matches first match of regx


String before(char *regx); // returns string before regx
String after(char *regx); // returns string after regx
String mid(int startIndex = 0, int length = 0);

bool isNull();
bool isInteger();
bool isInteger(int pos);
bool isNumeric();
bool isNumeric(int pos);
bool isEmpty(); // same as length() == 0
bool isUpperCase();
bool isUpperCase(int pos);
bool isLowerCase();
bool isLowerCase(int pos);
bool isWhiteSpace();
bool isWhiteSpace(int pos);
bool isBlackSpace();
bool isBlackSpace(int pos);
bool isAlpha();
bool isAlpha(int pos);
bool isAlphaNumeric();
bool isAlphaNumeric(int pos);
bool isPunct();
bool isPunct(int pos);
bool isPrintable();
bool isPrintable(int pos);
bool isHexDigit();
bool isHexDigit(int pos);
bool isCntrl();
bool isCntrl(int pos);
bool isGraph();
bool isGraph(int pos);

void clear();
int toInteger();
long parseLong();

double toDouble();
String token(char separator = ' '); // see also
StringTokenizer, explode()
String crypt(char *original, char *salt);
String getline(FILE *infp = stdin); // see also putline()
//String getline(fstream *infp = stdin); // see also putline()

void putline(FILE *outfp = stdout); // see also getline()


//void putline(fstream *outfp = stdout); // see also getline()

void swap(String aa, String bb); // swap aa to bb


String *sort(String aa[]); // sorts array of strings
String sort(int startIndex = 0, int length = 0); // sorts
characters inside a string
int freq(char ch); // returns the number of distinct,
nonoverlapping matches
void Format(const char *fmt, ...);
String replace (int startIndex, int endIndex, String str);

void substring(int startIndex, int endIndex, bool dummy); //


Directly changes object
void reverse(bool dummy); // Directly changes object. dummy to
get different signature
String deleteCharAt(int loc, bool dummy); // Directly changes
object
String deleteStr(int startIndex, int endIndex, bool dummy);
void trim(bool dummy); // Directly changes object. dummy to
get different signature
String insert(int index, String str2);
String insert(int index, String str2, bool dummy); // Directly
changes object
String insert(int index, char ch);
String insert(int index, char ch, bool dummy); // Directly
changes object
String insert(char *newstr, int start = 0, int length = 0,
char padchar = ' ');

String dump(); // Dump the string like 'od -c' (octal dump)
does

// required by java's StringBuffer


void ensureCapacity(int capacity);
void setLength(int len);
void setCharAt(int where, char ch); // see also charAt(),
getCharAt()

// required by java's Integer class, Long, Double classes


int parseInt(String ss) {return ss.toInteger();}
int parseInt(char *ss)
{String tmpstr(ss); return tmpstr.toInteger();}
long parseLong(String ss) {return ss.parseLong();}
long parseLong(char *ss)
{String tmpstr(ss); return tmpstr.parseLong();}
float floatValue() {return (float) toDouble(); }
double doubleValue() {return toDouble(); }
char * number2string(int bb); // see also String(int)
char * number2string(long bb); // see also String(long)
char * number2string(unsigned long bb); // see also
String(long)
char * number2string(double bb); // see also String(double)

///////////////////////////////////////////////
// List of duplicate function names
///////////////////////////////////////////////
// char * c_str() // use val()
// bool find(); // Use regionMatches()
// bool search(); // Use regionMatches()
// bool matches(); // Use regionMatches()
// int rindex(String str2, int startIndex = 0); Use
lastIndexOf()
// String blanks(int slength); // Use repeat()
// String append(String str2); // Use concat() or + operator
// String prepend(String str2); // Use + operator. See also
append()
// String split(char separator = ' '); // Use token(),
explode() or StringTokenizer class
bool contains(char *str2, int startIndex = 0); // use
indexOf()
// void empty(); Use is_empty()
// void vacuum(); Use clear()
// void erase(); Use clear()
// void zero(); Use clear()
// bool is_float(); Use is_numeric();
// bool is_decimal(); Use is_numeric();
// bool is_Digit(); Use is_numeric();
// float float_value(); Use toDouble();
// float tofloat(); Use toDouble();
// double double_value(); Use toDouble();
// double numeric_value(); Use toDouble();
// int int_value(); Use toInteger()
// int tonumber(); Use toInteger()
// String get(); Use substring() or val() but prefer java's
substring
// String getFrom(); Use substring() or val() but prefer
java's substring
// String head(int len); Use substring(0, len)
// String tail(int len); Use substring(length()-len, length())
// String cut(); Use deleteCharAt() or deleteStr()
// String cutFrom(); Use deleteCharAt() or deleteStr()
// String paste(); Use insert()
// String fill(); Use replace()
// char firstChar(); // Use substring(0, 1);
// char lastChar(); // Use substring(length()-1, length());
// String findNext(); Use token(), explode() or
StringTokenizer class

// begin(); iterator. Use operator [ii]


// end(); iterator. Use operator [ii]
// copy(); Use assignment = operator, String aa = bb;
// clone(); Use assignment = operator, String aa = bb;
// void putCharAt(int where, char ch); Use setCharAt()
// void replaceCharAt(int where, char ch); Use setCharAt()
// char getCharAt(int where); Use CharAt()
// void parseArgs(int where, char ch); Use StringTokensizer
class, token() or explode()
// void truncate(); Use trim(), rtrim(), chop() or chopall()
// convert number to string notostring(), int2str, long2str
Use number2string()

// All Operators ...


String operator+ (const String & rhs);
friend String operator+ (const String & lhs, const String &
rhs);

String& operator+= (const String & rhs); // using reference


will be faster
String& operator= (const String & rhs); // using reference
will be faster
bool operator== (const String & rhs); // using reference will
be faster
bool operator== (const char *rhs);
bool operator!= (const String & rhs);
bool operator!= (const char *rhs);
char operator [] (unsigned long Index) const;
char& operator [] (unsigned long Index);
friend ostream & operator<< (ostream & Out, const String &
str2);
friend istream & operator>> (istream & In, String & str2);
//do later: static list<String> explodeH;
// list head

protected:
char *sval; // Not safe to make sval public
void verifyIndex(unsigned long index) const; // not "inline"
because MS Win32 complains
void verifyIndex(unsigned long index, char *aa) const;// not
"inline" - MS Win32 complains

void _str_cat(char bb[]);


void _str_cat(int bb);
void _str_cat(unsigned long bb);
void _str_cat(float bb);

void _str_cpy(char bb[]);


void _str_cpy(int bb); // itoa
void _str_cpy(unsigned long bb);
void _str_cpy(float bb); // itof

private:
// Note: All the private variables and functions begin
// with _ (underscore)

//static String *_global_String; // for use in add operator


//inline void _free_glob(String **aa);

bool _equalto(const String & rhs, bool type = false);


bool _equalto(const char *rhs, bool type = false);
String *_pString; // temporary pointer for internal use..
char *_pNumber2String; // temporary pointer for internal
use..
inline void _allocpString();
inline void _allocpNumber2String();
inline void Common2AllCstrs();
inline void _reverse();
inline void _deleteCharAt(int loc);
inline void _deleteStr(int startIndex, int endIndex);
inline void _trim();
inline void _ltrim();
inline void _rtrim();
inline void _substring(int startIndex, int endIndex);
void _roundno(double input_dbl, float input_flt, short
precision, bool type);
};

// Global variables are defined in String.cpp

#endif // __STRING_H_ALDEV_

7.1 StringBuffer.h
//
// Author : Al Dev Email: [email protected]
//

#ifndef __STRINGBUFFER_H_ALDEV_
#define __STRINGBUFFER_H_ALDEV_

// Imitate Java's StringBuffer object


// This class is provided so that the Java code is
// portable to C++, requiring minimum code changes
// Note: While coding in C++ DO NOT use this class StringBuffer,
// this is provided only for compiling code written in Java
// which is cut/pasted inside C++ code.
class StringBuffer: public String
{
public:
StringBuffer();
~StringBuffer();
StringBuffer(char *aa);
StringBuffer(int size);
StringBuffer(String str);

int capacity();
StringBuffer append(String str2);
// See also operator +
//{ *this += str2; return *this;} // This is causing
core dumps...

StringBuffer append(char *str2);


StringBuffer append(int bb);
StringBuffer append(unsigned long bb) ;
StringBuffer append(float bb) ;
StringBuffer append(double bb) ;

StringBuffer insert(int index, String str2);


StringBuffer insert(int index, char ch);

StringBuffer reverse();

// Java's "delete()". Cannot use name delete in C++


StringBuffer deleteStr(int startIndex, int endIndex);
StringBuffer deleteCharAt(int loc);

StringBuffer substring(int startIndex, int endIndex = 0);


void assign(char *str);

private:
StringBuffer *_pStringBuffer;
inline void allocpStringBuffer();
inline void Common2AllCstrs();
};

#endif // __STRINGBUFFER_H_ALDEV_
7.2 StringTokenizer.h

//
// Author : Al Dev Email: [email protected]
//

#ifndef __STRINGTOKENIZER_H_ALDEV_
#define __STRINGTOKENIZER_H_ALDEV_

// Imitate java's StringTokenizer class


// provided to compile java code in C++ and vice-versa
class StringTokenizer: public String
{
public:
StringTokenizer(String str);
StringTokenizer(String str, String delimiters);
StringTokenizer(String str, String delimiters, bool
delimAsToken);
~StringTokenizer();

int countTokens();
bool hasMoreElements();
bool hasMoreTokens();
String nextElement(); // in java returns type 'Object'
String nextToken();
String nextToken(String delimiters);
private:
int CurrentPosition; // current index on string
int TotalTokens;
int RemainingTokens;
char * ListOfDl; // list of delimiters
char * WorkStr; // temp work string
char * OrigStr; // original string passed
bool DlFlag; // delimiter flag
inline void vPrepWorkStr(char *delimiters = NULL);
};

#endif // __STRINGTOKENIZER_H_ALDEV_

8. Renaming the String class


8.1 Case 1: Simple rename
If you do not like the String class name then you can use "typedef" to rename the
String class.

In all the files where you do include String.h, insert these lines:
// If you do not like the class name String, then you can rename using typedef
typedef String StringSomethingElseIwant;

// Your remaing code may be like this ....


int main()
{
StringSomethingElseIwant aa_renstr;
aa_renstr = "I renamed the String Class using typedef";

.......etc...
}

See the example_String.cpp.

8.2 Case 2: Resolve conflict


If there is a conflict with another class-name having the same name, and you want to
use both this class and conflicting class then you use this technique - in all the files
where you do include String.h, insert these lines:

#define String String_somethingelse_which_I_want


#include "String.h"
#undef String

#include "ConflictingString.h" // This also has String class...

// All your code goes here...


main()
{
String_somethingelse_which_I_want aa;
String bb; // This string class from conflicting string class

aa = " some sample string";


bb = " another string abraka-dabraka";
.......
}

The pre-processor will replace all literals of String to


"String_somethingelse_which_I_want" and immdiately undefines String. After undef
the conflicting string class header file is included which defines the "String" class.

9. File Class
You would use the File class to manipulate the operating system files. This class is an
imitation of Java's File class and will be very useful in C++ programming. Using this
File class in C++ you can do if file exists() ?, if directory exists() ?, file length() and
other functions.

 C++ File class is at


File.h http://www.angelfire.com/country/aldev0/cpphowto/File.h and
File.cpphttp://www.angelfire.com/country/aldev0/cpphowto/File.cpp
 Java java.io.File class
definition http://java.sun.com/j2se/1.3/docs/api/java/io/File.html
 Quick Reference on File
Class http://unicornsrest.org/reference/java/qref11/java.io.File.html
 File Class
summary http://www.idi.ntnu.no/~database/SIF8020/java-api/java.io.File.htm
l

10. C++ Zap (Delete) function


The delete and new operators in C++ are much better than the malloc and free
functions of C. Consider using new and zap (delete function) instead of malloc and
free as much as possible.

To make delete operators even more cleaner, make a Zap() inline function. Define a
zap() function like this:

// Put an assert to check if x is NULL, this is to catch


// program "logic" errors early. Even though delete works
// fine with NULL by using assert you are actually catching
// "bad code" very early

// Defining Zap using templates


// Use zap instead of delete as this will be very clean
template <class T>
inline void zap(T & x)
{
{assert(x != NULL);}
delete x;
x = NULL;
}

// In C++ the reason there are 2 forms of the delete operator is - because
// there is no way for C++ to tell the difference between a pointer to
// an object and a pointer to an array of objects. The delete operator
// relies on the programmer using "[]" to tell the two apart.
// Hence, we need to define zaparr function below.
// To delete array of pointers
template <class T>
inline void zaparr(T & x)
{
{assert(x != NULL);}
delete [] x;
x = NULL;
}

The zap() function will delete the pointer and set it NULL. This will ensure that even
if multiple zap()'s are called on the same deleted pointer then the program will not
crash. Please see the function zap_example() in example_String.cpp.

// See zap_example() in example_String.cpp


zap(pFirstname);
//zap(pFirstname); // no core dumps. Because pFirstname is NULL now
//zap(pFirstname); // no core dumps. Because pFirstname is NULL now

zap(pLastname);
zap(pJobDescription);

int *iiarray = new int[10];


zaparr(iiarray);

There is nothing magical about this, it just saves repetative code, saves typing time
and makes programs more readable. The C++ programmers often forget to reset the
deleted pointer to NULL, and this causes annoying problems causing core dumps and
crashes. The zap() takes care of this automatically. Do not stick a typecast in the zap()
function -- if something errors out on the above zap() function it likely has another
error somewhere.

Also my_malloc() , my_realloc() and my_free() should be used instead of malloc(),


realloc() and free(), as they are much cleaner and have additional checks. For an
example, see the file "String.h" which is using the my_malloc() and my_free()
functions.

WARNING : Do not use free() to free memory allocated with 'new' or 'delete' to free
memory allocated with malloc. If you do, then results will be unpredictable.

See the zap examples in example_String.cpp.


11. Pointers are problems
Pointers are not required for general purpose programming. In modern languages like
Java there is no support for pointers (Java internally uses pointers). Pointers make the
programs messy and programs using pointers are very hard to read.

Avoid using pointers as much as possible and use references. Pointers are really a
great pain. It is possible to write an application without using pointers. You should
pointers only in those cases where references will not work.

A reference is an alias; when you create a reference, you initialize it with the name of
another object, the target. From the moment on, the reference acts as an alternative
name of the target, and anything you do to the reference is really done to the target.

Syntax of References: Declare a reference by writing the type, followed by the


reference operator (&), followed by the reference name. References MUSTbe
initialized at the time of creation. For example -

int weight;
int & rweight = weight;

DOG aa;
DOG & rDogRef = aa;

Do's of references -

 Do use references to create an alias to an object


 Do initialize all references
 Do use references for high efficiency and performance of program.
 Do use const to protect references and pointers whenever possible.

Do not's of references -

 IMPORTANT: Don't use references to NULL objects


 Don't confuse the address of operator & with reference operator. The references
are used in the declarations section (see Syntax of References above).
 Don't try to reassign a reference
 Don't use pointers if references will work
 Don't return a reference to a local object
 Don't pass by reference if the item referred to may go out of scope
12. Usage of my_malloc and my_free
Try to avoid using malloc and realloc as much as possible and
use new and zap(delete). But sometimes you may need to use the "C" style memory
allocations in "C++". Use the functions my_malloc() , my_realloc() and my_free().
These functions do proper allocations and initialisations and try to prevent memory
problems. Also these functions (in DEBUG mode) can keep track of memory
allocated and print total memory usage before and after the program is run. This tells
you if there are any memory leaks.

The my_malloc and my_realloc is defined as below. It allocates little more memory
(SAFE_MEM = 5) and initializes the space and if it cannot allocate it exits the
program. The 'call_check(), remove_ptr()' functions are active only when
DEBUG_MEM is defined in makefile and are assigned to ((void)0) i.e. NULL for
non-debug production release. They enable the total-memory used tracing.

void *local_my_malloc(size_t size, char fname[], int lineno)


{
size_t tmpii = size + SAFE_MEM;
void *aa = NULL;
aa = (void *) malloc(tmpii);
if (aa == NULL)
raise_error_exit(MALLOC, VOID_TYPE, fname, lineno);
memset(aa, 0, tmpii);
call_check(aa, tmpii, fname, lineno);
return aa;
}

char *local_my_realloc(char *aa, size_t size, char fname[], int lineno)


{
remove_ptr(aa, fname, lineno);
unsigned long tmpjj = 0;
if (aa) // aa != NULL
tmpjj = strlen(aa);
unsigned long tmpqq = size + SAFE_MEM;
size_t tmpii = sizeof (char) * (tmpqq);
aa = (char *) realloc(aa, tmpii);
if (aa == NULL)
raise_error_exit(REALLOC, CHAR_TYPE, fname, lineno);

// do not memset memset(aa, 0, tmpii);


aa[tmpqq-1] = 0;
unsigned long kk = tmpjj;
if (tmpjj > tmpqq)
kk = tmpqq;
for ( ; kk < tmpqq; kk++)
aa[kk] = 0;
call_check(aa, tmpii, fname, lineno);
return aa;
}

See my_malloc.cpp. and the header file my_malloc.h. for full implementation of the
my_malloc program.

An example on usage of my_malloc and my_free as below:

char *aa;
int *bb;
float *cc;
aa = (char *) my_malloc(sizeof(char)* 214);
bb = (int *) my_malloc(sizeof(int) * 10);
cc = (float *) my_malloc(sizeof(int) * 20);

aa = my_realloc(aa, sizeof(char) * 34);


bb = my_realloc(bb, sizeof(int) * 14);
cc = my_realloc(cc, sizeof(float) * 10);

Note that in my_realloc you do not need to cast the datatype as the variable itself is
passed and correct my_realloc is called which returns the proper datatype pointer.
The my_realloc has overloaded functions for char*, int* and float*.

12.1 Garbage Collector for C++


In C/C++ Garbage Collection is not a standard feature and hence allocating and
freeing storage explicitly is difficult, complicated and is error-prone. TheGarbage
Collection (GC) is not part of the C++ standard because there are just so many ways
how one could implement it; there are many GC techniques, and deciding to use a
particular one would not be good for certain programs. Computer scientists had
designed many GC algorithms, each one of them catering to a particular problem
domain. There is no one single generic GC which will tackle all the problem domains.
As a consequence, GC is not part of C++ standard, they just left it out. Still, you
always have the choice of many freely available C++ libraries that do the job for you.

Visit the C++ Garbage Collection and Memory management site.

13. Debug files


To debug any C++ or C programs include the file debug.h and in your 'Makefile'
define DEBUG_STR, DEBUG_PRT, DEBUG_MEM to turn on the traces from the
debug.h functions. When you remove the '-DDEBUG_STR' etc.. then the debug
function calls are set to ((void)0) i.e. NULL, hence it has no impact on final
production release version of project. You can generously use the debug functions in
your programs and it will not increase the size of production executable.

See the file debug.cpp for implementation of debug routines. And see the
file my_malloc.cpp for sample which uses debug.h and debug functions.

See the sample Makefile .

14. Java like API


Visit the following sites for Java like API for C++

 Java utils in C++ http://www.pulsar.org/users/ej/archive/oop


 PhD Thesis book Java API in C++ http://www.pulsar.org/archive/phd/ejphd

15. IDE tools for C++


The following IDE tools (Integrated Development Environment) are available for C+
+:

 The "top rated" Dev-C++ is an full-featured Integrated Development


Environment (IDE) for both Win32 and Linux. It uses GCC, Mingw or Cygwin as
compiler and libraries set. It is at http://www.bloodshed.net/devcpp.html and
at mirror-site
 KDE Kdevelop
 Blatura site C++ Tools
 Amulet Amulet
 App Dev suite Angoss
 Make replacement Brass
 S/W product metrics CCC
 Project mgmt, edit, compile, debug C-Forge
 Dev environment Code Crusader
 Graphic gdb Code Medic
 Code analysis CodeWizard
 Gen HTML, LaTex for C++ cod Doc C++
 GUI toolkit openGL Ftk
 C++ and Java IDE GLG IDE
 HP IDE HP Eloquence
 IDE C++, Java, Pascal RHIDE
 IDE for C++, Java SNiff
 IDE for C++, Java Wipeout
 X-based dev env XWPE

16. C++ Online Textbooks and Docs


 "C++ Annotations" online book main site: Annotations better site : mirror-site
 "Teach Yourself C++ in 21 days" online textbook Teach C++
 "C++ Online" Textbook C++ Bruce Eckel
 C++ Open books: Panorama and click on Open Books.
 "Who's Afraid of C++?" online textbook Steveheller
 "Introduction to Object Oriented Programming" an ebook C++ OOP
 C++ in Hypertext C++ Hypertext
 Object Oriented Systems OOP article
 Porting C++ to Java PortingC
 C/C++ Journals UtahJournals
 Yahoo C++ category site CCyahoo
 C Library Reference Guide c_guide
 Online textbooks C++/Java FreeLib

Java books which will be useful for C++ programmers:

 Great Web reference site WebRef


 Many java books JBooks
 Intro to Java V3.0 JavaNotes mirror JavaNotes
 Web Library: http://www.itlibrary.com
 Intermediate Level Java book: http://www.bruceeckel.com
 Thinking in Java : Thinking C++
 John Hopkins Univ - Java resources Hall
 online java tutorial Chortle
 Practical guide for Java SunBooks
 Java Soton

17. C++ Coding Standards


Coding standard is very essential for readability and maitainence of programs. And it
also greatly inproves the productivity of the programmer. The GNU C++
compiler must enforce coding discipline. The following is suggested - inside class
definition:

 All public variables must begin with m like mFooVar. The m stands
for member.
 All protected variables must begin with mt, like mtFooVar and methods with t,
like tFooNum(). The t stands for protected.
 All private variables must begin with mv, like mvFooVar and methods with v,
like vFooLone(). The v stands for private.
 All public, protected and private variables must begin with uppercase
after m like F in mFooVar.
 All pointer variables must be prefixed with p, like
o Public variables mpFooVar and methods like FooNum()
o Protected variables mtpFooVar and methods with t like tFooNum()
o Private variables mvpFooVar and methods with v like vFooNum()

The compiler should generate error if the code does not follow above standard. The
C++ compiler can provide a flag option to bypass strict coding standard to compile
old source code, and for all new code being developed will follow the uniform world-
wide coding standard.

In the sample code given below t stands for protected, v stands for private, m stands
for member-variable and p stands for pointer.

class SomeFunMuncho
{
public:
int mTempZimboniMacho; // Only temporary variables should
be public as per OOP
float *mpTempArrayNumbers;
int HandleError();
float getBonyBox(); // Public accessor as per OOP design
float setBonyBox(); // Public accessor as per OOP design
protected:
float mtBonyBox;
int *mtpBonyHands;
char *tHandsFull();
int tGetNumbers();
private:
float mvJustDoIt;
char mvFirstName[30];
int *mvpTotalValue;
char *vSubmitBars();
int vGetNumbers();
};

When your program grows by millions of lines of code, then you will greatly
appreciate the naming convention as above. The readability of code improves,
because just by looking at the variable name like mvFirstName you can tell that it is
member of a class and is a private variable.

Visit the C++ Coding Standards URLs

 C++ FAQ Lite - Coding


standards http://new-brunswick.net/workshop/c++/faq/coding-
standards.html
 Rice university coding
standard http://www.cs.rice.edu/~dwallach/CPlusPlusStyle.html
 Identifiers to avoid in C++
Programs http://oakroadsystems.com/tech/cppredef.htm
 Coding standards from
Possibility http://www.possibility.com/Cpp/CppCodingStandard.html and mirr
or site
 Coding standards for Java and C++ from
Ambysoft http://www.ambysoft.com/javaCodingStandards.html
 Rules and recommendations http://www.cs.umd.edu/users/cml/cstyle/
 Indent and annotate http://www.cs.umd.edu/users/cml/cstyle/indhill-
annot.html
 Elemental rules http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules.html
 C++ style doc http://www.cs.umd.edu/users/cml/cstyle/Wildfire-C+
+Style.html
 C++ Coding Standards by Brett
Scolcum http://www.skypoint.com/~slocum/prog/cppstds.html
 Logikos C++ Coding
Standards http://www.logikos.com/standards/cpp_std.html
 NRad C++ coding
standards http://cadswes.colorado.edu/~billo/standards/nrad
 BEJUG C++ coding
standards http://www.meurrens.org/ip-Links/java/joodcs/ToddHoff.html
 Arctic Labs coding standards http://www.arcticlabs.com/codingstandards
See also

 For rapid navigation with ctags Vim color text editor


 To improve productivity see C++ Beautifier HOWTO

18. C++ Online Docs


There are MORE THAN ONE MILLION online articles/textbooks/reference guides
on C++ language. That is because C++ is used extensively for a very long period of
time. You can find them using the Internet search engines like Yahoo, Lycos, Excite
etc..

Visit the following C++ sites :-

 C++ STL basic string


class http://www.sgi.com/Technology/STL/basic_string.html
 See the section STL References
 C++ Crash-proof site http://www.troubleshooters.com/codecorn/crashprf.htm
 C++ Memory site http://www.troubleshooters.com/codecorn/memleak.htm
 GNU Main site http://www.gnu.org and gnu C++ site
at http://www.gnu.org/software/gcc/gcc.html
 GNU C++ Library - socs http://www.socs.uts.edu.au/doc/gnuinfo/libg++/libg+
+_18.html
 GNU C++ Library - gsi http://www.gsi.de/doc/gnu/libg++_toc.html
 GNU C++ Library - techno http://www.techno.spb.ru/~xbatob/FAQ/GNU/libg+
+_toc.html
 GNU C++ Library - utah http://www.math.utah.edu/docs/info/libg++_toc.html
 AS University C++ Standard String
class http://www.eas.asu.edu/~cse200/outline
 Java JString for C+
+ http://www.mike95.com/c_plusplus/classes/JString/JString_cpp.asp
 C++ Language Reference http://www.msoe.edu/~tritt/cpplang.html
 C++ Program examples and
samples http://www.msoe.edu/~tritt/cpp/examples.html
 Neil's C++ stuff http://www.cyclone7.com/cpp

Internet has vast amounts of documentation on C++. Visit the search engines like
Yahoo, Lycos, Infoseek, Excite. Type in the keywords 'C++ tutorials' 'C++
references' 'C++ books' . You can narrow down the search criteria by clicking
on Advanced search and select search by exact phrase
 http://www.yahoo.com
 http://www.lycos.com
 http://www.infoseek.com
 http://www.excite.com
 http://www.mamma.com

18.1 C++ Tutorials


There are many on-line tutorials available on internet. Type 'C++ tutorials' in the
search engine.

 C++ Tutorial http://www.xploiter.com/programming/c/index.shtml


 C++ Tutorial IISc,
India http://www.csa.iisc.ernet.in/Documentation/Tutorials/StyleGuides/c++-
style.html
 C++ Tutorial Brown
Univ http://wilma.cs.brown.edu/courses/cs032/resources/C++tutorial.html
 C++ Tutorial http://home.msuiit.edu.ph/~ddd/tutorials/cpp/cpplist.htm
 C++ Tutorial
IOstreams http://osiris.sunderland.ac.uk/~cs0pdu/pub/com365/Sched3/
iocpp.html

18.2 Useful links


Bird's eye view of C++ URLs (about 153 url
links) http://www.enteract.com/~bradapp/links/cplusplus-links.html

This URL: http://www.snippets.org portable C code contains over 360 files.

18.3 C++ Quick-Reference


Type 'C++ Reference' in the search engine.

 C++ quick ref http://www.cs.jcu.edu.au/~david/C++SYNTAX.html


 C++ Standard Library Quick
Reference http://www.halpernwightsoftware.com/stdlib-scratch/quickref.htm
l
 C++ STL from
halper http://www.halpernwightsoftware.com/stdlib-scratch/quickref.html
18.4 C++ Usenet Newsgroups
 C++ newsgroups : comp.lang.c++.announce
 C++ newsgroups : comp.lang.c++.*
 C++ newsgroups : http://marshall-cline.home.att.net/cpp-faq-lite

19. Memory Tools


Use the following memory debugging tools

 The "MPatrol" is a very powerful memory debugging tool. It is


at http://www.cbmamiga.demon.co.uk/mpatrol and
at http://www.rpmfind.net go here and search mpatrol. If you are using linux
then you must download the mpatrol*.src.rpm file from the rpmfind.net. To
update the mpatrol*.src.rpm to latest version, you can use the old
mpatrol.spec file and latest mpatrol*.tar.gz file to rebuild new *.src.rpm.
 On linux contrib cdrom see mem_test*.rpm package and
at http://www.rpmfind.net go here and search mem_test.
 On linux cdrom see ElectricFence*.rpm package and
at http://www.rpmfind.net go here and search electricfence.
 Purify Tool from Rational Software Corp http://www.rational.com
 Insure++ Tool from Parasoft Corp http://www.parasoft.com
 Linux Tools at http://www.xnet.com/~blatura/linapp6.html#tools
 Search the Internet engines like Yahoo, Lycos, Excite, Mamma.com for
keyword "Linux memory debugging tools".

20. Related URLs


You MUST use a color editor like 'Vim' (Vi improved) while coding in C++. Color
editors greatly increase your productivity. Visit the URL for Vim howto below.

Visit following locators which are related to C, C++ -

 Vim color text editor for C++, C http://metalab.unc.edu/LDP/HOWTO/Vim-


HOWTO.html
 C++ Beautifier HOWTO http://metalab.unc.edu/LDP/HOWTO/C-C++Beautifier-
HOWTO.html
 Source code control system for C++ programs (CVS
HOWTO) http://metalab.unc.edu/LDP/HOWTO/CVS-HOWTO.html
 Linux goodies main site is at http://www.aldev.8m.com Mirror sites are at
- http://aldev0.webjump.com, angelfire, geocities, virtualave, 50megs, theglob
e,NBCi, Terrashare, Fortunecity, Freewebsites, Tripod, Spree, Escalix, Httpcity,
Freeservers.

21. C++ Scripting Languages


The major disadvantage of C++ is that you must recompile and link the object files to
create a executable anytime you make a small change. The compile/link/debug cycles
take away a lot of time and is quite unproductive. Since modern CPU's and RAM are
becoming extremely fast and cheap, it is better to spend more money on hardware and
use scripting languages for development.

21.1 PIKE (C/C++ Scripting Language)


The scripting language like PIKE eliminates the linking and re-compiling and will
really speed up the development process.

As memory (RAM) prices are dropping and CPU speeds are increasing, scripting
language like PIKE will EXPLODE in popularity. PIKE will become most widely
used scripting language as it is object oriented and it's syntax is very identical to that
of C++ language.

Programming productivity will increase by five times by using the Pike C++ scripting
language. And Pike is very useful for 'proof of concept' and developing prototypes
rapidly.

The Pike is at http://pike.roxen.com and at http://www.roxen.com.

The Roxen Web server is completely written in Pike, which demonstrates how
powerful Pike is. Pike runs much faster than Java for some operations and is quite
efficient in using memory resources.

21.2 SoftIntegration Ch (C/C++ Scripting Language)


If you want commercial scripting language, get the 'Ch scripting' product from
SoftIntegration corporation at http://www.softintegration.com.

The scripting language environment called Ch is a superset of C with high-level


extensions, and salient features from C++ and other languages so that users can learn
the language once and use it anywhere for almost any programming purposes. This C-
compatible scripting language environment is also a middleware serving as crucial
software infrastructure for running portable applications in heterogeneous platforms.
The portable Ch code can be deployed safely over the internet or intranets to run
anywhere ranging from supercomputers, workstations, PCs, Palm Pilots, PDA, to non-
traditional computing devices such as CNC machines, robots, TVs, refrigerators,
among others.

21.3 PHP (C++ Scripting Language)


PHP is hypertext-preprocessor scripting language and is very rapidly evolving and
getting object oriented features. It has the "class" keyword through which it tries to
implement object oriented scripting. May be in near future PHP will mature rapidly to
become a robust scripting language for object oriented projects. In future it will tackle
both the web applications and general purpose applications. Why have different
scripting languages for web and general applications, instead just use PHP for both.
PHP is at http://www.linuxdoc.org/HOWTO/PHP-HOWTO.html.

22. Templates
 http://babbage.cs.qc.edu/STL_Docs/templates.htm Mirror
at: http://www.mike95.com/c_plusplus/tutorial/templates
 This tells about #pragma template :
- http://www.dgp.toronto.edu/people/JamesStewart/270/9697f/notes/Nov25
-tut.html
 Very GOOD site: http://www.cplusplus.com/doc/tutorial/tut5-
1.html http://www.cplusplus.com/doc/tutorial
 For certification of C++: goto http://examware.com and click on "Tutorials"
and then C/C++ button
 C++ Open books: http://www.softpanorama.org/Lang/cpp.shtml and click on
tutorials
 Templates
tutorial
: http://www.infosys.tuwien.ac.at/Research/Component/tutorial/prwmain.ht
m

23. STL References


Please visit the following sites for STL -
 Very good intro to
iterators http://www.cs.trinity.edu/~joldham/1321/lectures/iterators/
 CMU univ http://www.cs.cmu.edu/afs/andrew/course/15/129/Cpp/10-STL/
 Intro to STL SGI http://www.sgi.com/Technology/STL/stl_introduction.html
 Mumits STL Newbie
guide http://www.xraylith.wisc.edu/~khan/software/stl/STL.newbie.html Mu
mit Khan's informative STL introduction is full of
examples http://abel.hive.no/C++/STL/stlnew.html
 ObjectSpace examples: ObjectSpace has contributed over 300 examples to the
public domain and these are a very good start for
beginners.ftp://butler.hpl.hp.com/stl/examples.zip
 Joseph Y. Laurino's STL
page. http://weber.u.washington.edu/~bytewave/bytewave_stl.html
 Musser's STL docs and examples. Very
nice. http://www.cs.rpi.edu/~musser/stl.html
 STL Newbie home
site. http://www.xraylith.wisc.edu/~khan/software/stl/STL.newbie.html
 Marian Corcoran's STL FAQ. ftp://butler.hpl.hp.com/stl/stl.faq

STL Tutorial:

 The best doc on tutorial


- http://www.decompile.com/html/tut.html Mirror: http://mip.ups-tlse.fr/
~grundman/stl-tutorial/tutorial.html
 very good - http://www.yrl.co.uk/~phil/stl/stl.htmlx
 C++ Standard Template LibraryAnother great tutorial, by Mark
Sebern http://www.msoe.edu/eecs/cese/resources/stl/index.htm
 By Jak
Kirman: http://129.187.112.56/Misc/Computer/stl-tutorial/tutorial_9.html Mi
rrors
:http://www.cs.brown.edu/people/jak/proglang/cpp/stltut/tut.html http://
saturn.math.uaa.alaska.edu/~afjhj/cs403/stl/tutorial.html
 Technical University Vienna by Johannes
Weidl http://dnaugler.cs.semo.edu/tutorials/stl mirrorhttp://www.infosys.tuw
ien.ac.at/Research/Component/tutorial/prwmain.htm
 Colorful Tutorial http://www.codeproject.com/cpp/stlintroduction.asp

Ready-made Components for use with the STL


 STL components Collected by Boris
Fomitche http://www.metabyte.com/~fbp/stl/components.html

Main STL sites -

 C++ STL from SGI http://www.sgi.com/Technology/STL


 C++ STL from RPI univ http://www.cs.rpi.edu/projects/STL/htdocs/stl.html
 C++ STL site ODP for STL and the mirrorsite
 STL for C++
Programmers http://userwww.econ.hvu.nl/~ammeraal/stlcpp.html
 C++ STL from
halper http://www.halpernwightsoftware.com/stdlib-scratch/quickref.html

23.1 Overview of the STL


The STL offers the programmer a number of useful data structures and algorithms. It
is made up the following components.

 Containers. There are two types:


o Sequential. This group comprises the vector, list and dequeue types.
o Sorted Associative. This group comprises the set, map, multiset and
multimap types.
 Iterators. These are pointer like objects that allow the user to step through the
contents of a container.
 Generic Algorithms. The STL provides a wide range of efficently implemented
standard algorithms (for example find, sort and merge) that work with the
container types. (Some of the containers have special purpose
implementations of these algorithms as member functions.)
 Function Objects. A function object is an instance of a class that provides a
definition of operator(). This means that you can use such an object like a
function.
 Adaptors. The STL provides
o Container adaptors that allow the user to use, say, a vector as the basis
of a stack.
o Function adaptors that allow the user to construct new function objects
from existing function objects.
 Allocators. Every STL container class uses an Allocator class to hold
information about the memory model the program is using. I shall totally
ignore this aspect of the STL.
I will be considering the use of the vector, list, set and map containers. To make use of
these containers you have to be able to use iterators so I shall have something to say
about STL iterators. Using the set and map containers can mean having to supply a
simple function object to the instantiation so I shall also have something to say about
function objects. I will only briefly mention the algorithms supplied by the STL. I will
not mention adaptors at all.

I have taken liberties with some of the types of function arguments -- for example
most of the integer arguments referred to in what follows actually have type size_type
which is typedef'ed to an appropriate basic type depending on the allocation model
being used. If you want to see the true signatures of the various functions discussed
have a look at the Working Paper or the header files.

There are a number of utility classes supplied with the STL. The only one of
importance to us is the pair class. This has the following definition:

template<class T1, class T2>


class pair {
public:
T1 first;
T2 second;
pair(const T1& a, const T2& b) : first(a), second(b) {}

};

and there is a convenient function make_pair with signature:

pair<T1,T2> make_pair(const T1& f, const T2&,s)

as well as implementations of operator== and operator < . There is nothing


complicated about this template class and you should be able to use it without further
guidance. To use it #include the header file pair.h. It crops up in a number of places
but particularly when using the set and map classes.

23.2 Header Files


To use the various bits of the STL you have to #include the appropriate header files.
These may differ slightly from compiler to compiler but for g++ the ones of interest
are:
 vector.h for the vector type.
 list.h for the list type.
 set.h for the set type.
 map.h for the map type.
 algo.h for access to the generic algorithms.

If you don't want to remember which is which you could just use stl.h which includes
all the above (and all the other header files of the STL as well).

23.3 The Container Classes Interface


The container classes have many member functions that have the same names. These
functions provide the same (or very similar) services for each of the classes (though,
of course, the implementations will be different). The following table lists the
functions that we shall consider in more detail. A star opposite a function name
indicates that the container type heading the column provides a member function of
that name.

Container Class Interface

Purpose Vector List Set Map


Operation

== comparison * * * *

< comparison * * * *

begin iterator * * * *

end iterator * * * *

size no. of elements * * * *

empty is container empty * * * *

front first element * *

back last element * *

[] element access/modification * *

insert insert element(s) * * * *


push_back insert new last element * *

push_front insert new first element *

erase remove element(s) * * * *

pop_back remove last element * *

pop_front remove last element *

If the following discussion leaves something unclear (and it will) you can always
write a small test program to investigate how some function or feature behaves.

23.4 Vectors
A vector is an array like container that improves on the C++ array types. In particular
it is not neccessary to know how big you want the vector to be when you declare it,
you can add new elements to the end of a vector using the push_back function. (In
fact the insert function allows you insert new elements at any position of the vector,
but this is a very inefficent operation -- if you need to do this often consider using a
list instead).

Constructing Vectors

vector is a class template so that when declaring a vector object you have to state the
type of the objects the vector is to contain. For example the following code fragment

vector<int> v1;
vector<string> v2;
vector<FiniteAutomaton> v3;

declares that v1 is a vector that holds integers, v2 a vector that holds strings and v3
holds objects of type FiniteAutomaton (presumably an user defined class type). These
declarations do not say anything about how large the vectors are to be
(implementations will use a default starting size) and you can grow them to as large as
you require.

You can give an inital size to a vector by using a declaration like


vector<char> v4(26);

which says that v4 is to be vector of characters that initially has room for 26
characters. There is also a way to initailise a vector's elements. The declaration

vector<float> v5(100,1.0);

says that v5 is a vector of 100 floating point numbers each of which has been
initialised to 1.0.

Checking Up on Your Vector

Once you have created a vector you can find out the current number of elements it
contains by using the size function. This function takes no arguments and returns an
integer (strictly a value of type size_type, but this gets converted to an integer) which
says how many elements there are in the vector. What will be printed out by the
following small program?

<vector-size.cc>=
#include <iostream.h>
#include <vector.h>

void main()
{
vector<int> v1;
vector<int> v2(10);
vector<int> v3(10,7);

cout << "v1.size() returns " << v1.size() << endl;


cout << "v2.size() returns " << v2.size() << endl;
cout << "v3.size() returns " << v3.size() << endl;
}

To check on wether your vector is empty or not you can use the empty function. This
takes no arguments and returns a boolean value, true if the vector is empty, false if it
is not empty. What will be printed out by the following small program (true prints as 1
and false prints as 0)?

<vector-empty.cc>=
#include <iostream.h>
#include <vector.h>

void main()
{
vector<int> v1;
vector<int> v2(10);
vector<int> v3(10,7);

cout << "v1.empty() has value " << v1.empty() << endl;
cout << "v2.empty() has value " << v2.empty() << endl;
cout << "v3.empty() has value " << v3.empty() << endl;
}

Accessing Elements of a Vector

You can access a vector's elements using operator[]. Thus, if you wanted to print out
all the elements in a vector you could use code like

vector<int> v;
// ...
for (int i=0; i<v.size(); i++)
cout << v[i];

(which is very similar to what you might write for a builtin array).

You can also use operator[] to set the values of the elements of a vector.

vector<int> v;
// ...
for (int i=0; i<v.size(); i++)
v[i] = 2*i;

The function front gives access to the first element of the vector.

vector<char> v(10,'a');
// ...
char ch = v.front();

You can also change the first element using front.


vector<char> v(10,'a');
// ...
v.front() = 'b';

The function back works the same as front but for the last element of the vector.

vector<char> v(10,'z');
// ...
char last = v.back();
v.back() = 'a';

Here is a simple example of the use of [].

<vector-access.cc>=
#include <vector.h>
#include <iostream.h>

void main()
{
vector<int> v1(5);
int x;
cout << "Enter 5 integers (seperated by spaces):" << endl;
for (int i=0; i<5; i++)
cin >> v1[i];
cout << "You entered:" << endl;
for (int i=0; i<5; i++)
cout << v1[i] << ' ';
cout << endl;
}

Inserting and Erasing Vector Elements

Along with operator[] as described above there are a number of other ways to change
or access the elements in a vector.

 push_back will add a new element to the end of a vector.


 pop_back will remove the last element of a vector.
 insert will insert one or more new elements, at a designated position, in the
vector.
 erase will remove one or more elements from a vector between designated
positions.

Note that insert and erase are expensive operations on vectors. If you use them a lot
then you should consider using the list data structure for which they are more
efficient.

<vector-mod.cc>=
#include <iostream.h>
#include <vector.h>

void main()
{
vector<int> v;

for (int i=0; i<10; i++) v.push_back(i);


cout << "Vector initialised to:" << endl;
for (int i=0; i<10; i++) cout << v[i] << ' ' ;
cout << endl;

for (int i=0; i<3; i++) v.pop_back();


cout << "Vector length now: " << v.size() << endl;
cout << "It contains:" << endl;
for (int i=0; i<v.size(); i++) cout << v[i] << ' ';
cout << endl;

int a1[5];
for (int i=0; i<5; i++) a1[i] = 100;

v.insert(& v[3], & a1[0],& a1[3]);


cout << "Vector now contains:" << endl;
for (int i=0; i<v.size(); i++) cout << v[i] << ' ';
cout << endl;

v.erase(& v[4],& v[7]);


cout << "Vector now contains:" << endl;
for (int i=0; i<v.size(); i++) cout << v[i] << ' ';
cout << endl;
}

In the above a vector v has been declared then initialised using push_back. Then some
elements have been trimmed off it's end using pop_back. Next an ordinary integer
array has been created and then some of its elements inserted into v using insert.
Finally erase has been used to remove elements from v. The functions used above take
arguments as follows.
 push_back takes a single argument of the type of the elements held in the
vector.
 pop_back takes no arguments. It is a mistake to use pop_back on an empty
vector.
 insert has three forms:
o insert(pos, T& x) which will insert the single element x at position pos in
the vector.
o insert(pos, start, end) which inserts a sequence of elements from some
other container at position pos in the vector. The
o sequence of elements is identified as starting at the start element and
continuing to, but not including, the end element.
o insert(pos, int rep, T& x) inserts rep copies of x at position pos in the
vector.

As indicated in the code above the position pos should be the address of the element
to insert at, whilst the start and end arguments are likewise also addresses. (The true
story is that they are iterators -- see next subsection and following section).

 erase has two forms (pos, start and end have the same types as for the insert
function):
o erase(pos) which will remove the element at position pos in the vector.
o insert(start,end) which will remove elements starting at postion start
upto, but not including, the element at position end.

Vector Iterators

The simple way to step through the elements of a vector v is as we have done above:

for (int i=0; i<v.size(); i++) { ... v[i] ... }

Another way is to use iterators. An iterator can be thought of as a pointer into the
container, incrementing the iterator allows you to step through the container. For
container types other than vectors iterators are the only way to step through the
container.

For a vector containing elements of type T:


vector<T> v;

an iterator is declared as follows:

vector<T>::iterator i;

Such iterators are constructed and returned by the functions begin() and end(). You
can compare two iterators (of the same type) using == and !=, increment using ++ and
dereference using *. [In fact vector iterators allow more operations on them - see next
section for more information].

Here is an illustration of how to use iterators with vectors.

<vector-iterator.cc>=
#include <iostream.h>
#include <vector.h>

void main()
{
vector<int> v(10);
first is ``less'' than the second

int j = 1;

vector<int>::iterator i;

// Fill the vector v with integers 1 to 10.


i = v.begin();
while (i != v.end())
{
*i = j;
j++;
i++;
}

// Square each element of v.


for (i=v.begin(); i!=v.end(); i++) *i = (*i) * (*i);

// Print out the vector v.


cout << "The vector v contains: ";
for (i=v.begin(); i!=v.end(); i++) cout << *i << ' ';
cout << endl;

}
Note how *i can be used on the left-hand side of an assignment statement so as to
update the element pointed at by i, and on the right-hand side to access the current
value.

Comparing Vectors

You can compare two vectors using == and <. == will return true only if both vectors
have the same number of elements and all elements are equal. The < functions
performs a lexicographic comparison of the two vectors. This works by comparing the
vectors element by element. Suppose we are comparing v1 and v2 (that is v1 < v2?).
Set i=0. If v1[i] < v2[i] then return true, if v1[i] > v2[i] then return false, otherwise
increment i (that is move on to the next element). If the end of v1 is reached before v2
return true, otherwise return false. Lexicographic order is also known as dictionary
order. Some examples:

(1,2,3,4) < (5,6,7,8,9,10) is false.


(1,2,3) < (1,2,3,4) is true
(1,2,3,4) < (1,2,3) is false
(0,1,2,3) < (1,2,3) is true

The following code illustrates the third example above.

<vector-comp.cc>=
#include <vector.h>
#include <iostream.h>

void main()
{
vector<int> v1;
vector<int> v2;
for (int i=0; i<4; i++) v1.push_back(i+1);
for (int i=0; i<3; i++) v2.push_back(i+1);

cout << "v1: ";


for (int i=0; i<v1.size(); i++) cout << v1[i] << ' ';
cout << endl;

cout << "v2: ";


for (int i=0; i<v2.size(); i++) cout << v2[i] << ' ';
cout << endl;

cout << "v1 < v2 is: " << (v1<v2 ? "true" : "false") << endl;
}
The comparison operators <= and >= also work.

23.5 Iterators and the STL


See the section STL References

23.6 Lists
See the section STL References

23.7 Sets
The set container type allows an user to store and retrieve elements directly rather
than through an index into the container. The set container acts as a mathematical set
in that it holds only distinct elements. However unlike a mathematical set, elements in
a set container are held in (an user-supplied) order. In practise this is only a minor
restriction on treating a set container as an implementation of the mathematical set
abstract data type, and it allows for a much more efficent implementation than an
unordered approach.

Constructing Sets

Two template arguments are required to construct a set container -- the type of the
objects the set is to contain and a function object that can compare two elements of the
given type, that is:

set<T, Compare> s;

(The declaration set < T > s should also be possible -- it would use a default template
argument less < T > as the second argument, but many C++ compilers (including g+
+) cannot as yet cope with default template arguments.)

For simple types T we can use the function object less < T > ( without having to
worry about what a ``function object'' is), for example all the following are legal set
declarations.

set<int, less<int> > s1;


set<double, less<double> > s2;
set<char, less<char> > s3;
set<string, less<string> > s4;

(Note that the space between the two final >'s in the template is required - otherwise
the compiler will interpret >> as the right shift operator.) In each of these cases the
function object makes use of the operator < as defined for the the underlying type
(that is int, double, char and string).

The following code declares a set of integers, then adds some integers to the set using
the insert method and then prints out the set members by iterating through the set.
You will note that the set's contents are printed out in ascending order even though
they were added in no particular order.

<set-construct1.cc>=
#include <iostream.h>
#include <set.h>

void main()
{
set<int, less<int> > s;
set<int, less<int> >::iterator i;

s.insert(4);
s.insert(0);
s.insert(-9);
s.insert(7);
s.insert(-2);
s.insert(4);
s.insert(2);

cout << The set contains the elements: ;


for (i=s.begin(); i!=s.end(); i++) cout << *i << ' ';
cout << endl;
}

Note that 4 is added twice but only turns up once on the list of elements -- which is
what one expects of a set.

What are Function Objects?

One of the nifty features of C++ is the ability to overload operators, so that one can
have + mean whatever one likes for your newly designed class. One of the operators
C++ allows you to overload is the function call operator () and this allows you to
create classes whose instances can behave like functions in many ways. These are
function objects.

Here is a simple example.

<function-object.cc>=
#include <iostream.h>

template<class T>
class square {
public:
T operator()(T x) { return x*x; }
};
// This can be used with any T for which * is defined.

void main()
{
// Create some function objects.
square<double> f1;
square<int> f2;

// Use them.
cout << 5.1^2 = << f1(5.1) << endl;
cout << 100^2 = << f2(100) << endl;

// The following would result in a compile time error.


// cout << 100.1^2 = << f2(100.1) << endl;

Function objects are used in a number of places in the STL. In particular they are used
when declaring sets and maps.

The function object required for these purposes, let's suppose it is called comp, must
satisfy the following requirements.

1. If comp(x,y) and comp(y,z) are true for objects x, y and z then comp(x,z) is also
true.
2. comp(x,x) is false for every object x.

If for any particular objects x and y, both comp(x,y) and comp(y,x) are false then x
and y are deemed to be equal.

This, in fact, is just the behaviour of the strictly-less-than relation (ie < ) on numbers.
The function object less < T > used above is defined in terms of a < operator for the
type T. It's definition can be thought of as follows.
template<class T>
struct less {
bool operator()(T x, T y) { return x<y; }
}

(The actual definition uses references, has appropriate const annotations and inherits
from a template class binary_function.)

This means that if the type T has operator < defined for it then you can use less < T >
as the comparator when declaring sets of T. You might still want to use a special
purpose comparator if the supplied < operator is not appropriate for your purposes.
Here is another example. This defines a simple class with a definition of operator <
and a function object that performs a different comparison. Note that the overloaded <
and () operators should be given const annotations so that the functions work correctly
with the STL.

<set-construct2.cc>=
#include <iostream.h>
#include <set.h>

// This class has two data members. The overloaded operator< compares
// such classes on the basis of the member f1.
class myClass {
private:
int f1;
char f2;
public:
myClass(int a, char b) : f1(a), f2(b) {}
int field1() const { return f1; }
char field2() const { return f2; }
bool operator<(myClass y) const
{ return (f1<y.field1()); }
};

// This function object compares objects of type myClass on the basis


// of the data member f2.
class comp_myClass {
public:
bool operator()(myClass c1, myClass c2) const
{ return (c1.field2() < c2.field2()); }
};

void main()
{
set<myClass, less<myClass> > s1;
set<myClass, less<myClass> >::iterator i;
set<myClass, comp_myClass> s2;
set<myClass, comp_myClass>::iterator j;

s1.insert(myClass(1,'a'));
s2.insert(myClass(1,'a'));
s1.insert(myClass(1,'b'));
s2.insert(myClass(1,'b'));
s1.insert(myClass(2,'a'));
s2.insert(myClass(2,'a'));

cout << Set s1 contains: ;


for (i=s1.begin(); i!=s1.end(); i++)
{ cout << ( << (*i).field1() << ,
<< (*i).field2() << ) << ' ';
}
cout << endl;

cout << Set s2 contains: ;


for (j=s2.begin(); j!=s2.end(); j++)
{ cout << ( << (*j).field1() << ,
<< (*j).field2() << ) << ' ';
}
cout << endl;

The set s1 contains (1,a) and (2,a) as comparison is on the data member f1, so that
(1,a) and (1,b) are deemed the same element. The set s2 contains (1,a) and (1,b) as
comparison is on the data member f2, so that (1,a) and (2,a) are deemed the same
element.

A Printing Utility

The way we have printed out the sets in the previous examples is a little awkward so
the following header file containing a simple overloaded version ofoperator<< has
been written. It works fine for small sets with simple element types.

<printset.h>=
#ifndef _PRINTSET_H
#define _PRINTSET_H

#include <iostream.h>
#include <set.h>

template<class T, class Comp>


ostream& operator<<(ostream& os, const set<T,Comp>& s)
{
set<T,Comp>::iterator iter = s.begin();
int sz = s.size();
int cnt = 0;
os << {;
while (cnt < sz-1)
{
os << *iter << ,;
iter++;
cnt++;
}
if (sz != 0) os << *iter;
os << };

return os;
}
#endif

The use here of << as an output routine for a set assumes that << has been defined for
the set elements, and uses this to print a comma delimited list of the set elements
wrapped in curly braces. It will be used without comment in the following examples.

How Many Elements?

You can determine if a set is empty or not by using the empty() method. You can find
out how many elements there are in a set by using the size() method. These methods
take no arguments, empty() returns true or false and size() returns an integer.

<set-size.cc>=
#include <iostream.h>
#include <set.h>
#include printset.h

void main()
{
set<int, less<int> > s;

cout << The set s is


<< (s.empty() ? empty. : non-empty.) << endl;
cout << It has << s.size() << elements. << endl;

cout << Now adding some elements... << endl;

s.insert(1);
s.insert(6);
s.insert(7);
s.insert(-7);
s.insert(5);
s.insert(2);
s.insert(1);
s.insert(6);

cout << The set s is now


<< (s.empty() ? empty. : non-empty.) << endl;
cout << It has << s.size() << elements. << endl;
cout << s = << s << endl;
}

Checking the Equality of Sets.

Two sets may be checked for equality by using ==. This equality test works by testing
in order the corresponding elements of each set for equality using T::operator==.

<set-equality.cc>=
#include <iostream.h>
#include <set.h>
#include printset.h

void main()
{
set<int, less<int> > s1, s2 ,s3;

for (int i=0; i<10; i++)


{
s1.insert(i);
s2.insert(2*i);
s3.insert(i);
}

cout << s1 = << s1 << endl;


cout << s2 = << s2 << endl;
cout << s3 = << s3 << endl;
cout << s1==s2 is: << (s1==s2 ? true. : false.) << endl;
cout << s1==s3 is: << (s1==s3 ? true. : false.) << endl;
}

It is also possible to compare two sets using <. The comparison s1 < s2 is true if the
set s1 is lexicographically less than the set s2, otherwise it is false.

Adding and Deleting Elements

The way to add elements to a set is to use the insert method (as we have done above).
The way to delete elements from a set is to use the erase method.

For a set holding elements of type T these methods come in following forms:

 pair < iterator, bool> insert(T& x). This is the standard insert function. The
return value may be ignored or used to test if the insertion succeeded (that is
the element was not already in the set). If the insertion succeeded the
boolean component will be true and the iterator will point at the just inserted
element. If the element is already present the boolean component will be
false and the iterator will point at the element x already present.
 iterator insert(iterator position, T& x). This version of the insert function
takes, in addition to the element to insert, an iterator stating where the insert
function should begin to search. The returned iterator points at the newly
inserted element, (or the already present element).
 int erase(T& x). This version of the erase method takes an element to delete
and returns 1 if the element was present (and removes it) or 0 if the element
was not present.
 void erase(iterator position). This version takes an iterator pointing at some
element in the set and removes that element.
 void erase(iterator first, iterator last). This verion takes two iterators pointing
into the set and removes all the elements in the range [ first,last ] .

The following example illustrates these various forms.

<set-add-delete.cc>=
#include <iostream.h>
#include <set.h>
#include printset.h

void main()
{
set<int, less<int> > s1;

// Insert elements in the standard fashion.


s1.insert(1);
s1.insert(2);
s1.insert(-2);

// Insert elements at particular positions.


s1.insert(s1.end(), 3);
s1.insert(s1.begin(), -3);
s1.insert((s1.begin()++)++, 0);

cout << s1 = << s1 << endl;

// Check to see if an insertion has been successful.


pair<set<int, less<int> >::iterator,bool> x = s1.insert(4);
cout << Insertion of 4 << (x.second ? worked. : failed.)
<< endl;
x = s1.insert(0);
cout << Insertion of 0 << (x.second ? worked. : failed.)
<< endl;

// The iterator returned by insert can be used as the position


// component of the second form of insert.
cout << Inserting 10, 8 and 7. << endl;
s1.insert(10);
x=s1.insert(7);
s1.insert(x.first, 8);

cout << s1 = << s1 << endl;

// Attempt to remove some elements.


cout << Removal of 0 << (s1.erase(0) ? worked. : failed.)
<< endl;
cout << Removal of 5 << (s1.erase(5) ? worked. : failed.)
<< endl;

// Locate an element, then remove it. (See below for find.)


cout << Searching for 7. << endl;
set<int,less<int> >::iterator e = s1.find(7);
cout << Removing 7. << endl;
s1.erase(e);

cout << s1 = << s1 << endl;

// Finally erase everything from the set.


cout << Removing all elements from s1. << endl;
s1.erase(s1.begin(), s1.end());
cout << s1 = << s1 << endl;
cout << s1 is now << (s1.empty() ? empty. : non-empty.)
<< endl;
}

Finding Elements

We mention two member functions that can be used to test if an element is present in
a set or not.

 iterator find(T& x). This searches for the element x in the set. If x is found it
returns an iterator pointing at x otherwise it returns end().
 int count(T& x). This returns 1 if it finds x in the set and 0 otherwise. (The
count function for multisets returns the number of copies of the element in
the set which may be more than 1. Hence, I guess, the name of the function.)

The use of find has been illustrated above. We could use count to write a simple
template based set membership function. (This should also provide a version that
takes a reference to the argument x.)

<setmember.h>=
#ifndef _SETMEMBER_H
#define _SETMEMBER_H
#include <set.h>

template<class T, class Comp>


bool member(T x, set<T,Comp>& s)
{
return (s.count(x)==1 ? true : false);
}
#endif

Which might be used as follows.

<set-membership.cc>=
#include <iostream.h>
#include <set.h>
#include printset.h
#include setmember.h

void main()
{
set<int, less<int> > s;
for (int i= 0; i<10; i++) s.insert(i);
cout << s = << s << endl;
cout << 1 is << (member(1,s) ? : not) << a member of s
<< endl;
cout << 10 is << (member(10,s) ? : not) << a member of s
<< endl;
}

Set Theoretic Operations

The STL supplies as generic algorithms the set operations includes, union,
intersection, difference and symmetric diffference. To gain access to these functions
you need to include algo.h. (In what follows iter stands for an appropriate iterator).

 bool includes(iter f1,iter l1,iter f2,iter l2).

This checks to see if the set represented by the range [f2,l2] is included in the
set [f1,l1]. It returns true if it is and false otherwise. So to check to see if one
set is included in another you would use

includes(s1.begin(), s1.end(), s2.begin(), s2.end())

The includes function checks the truth of 3#3 ( that is of 4#4). This function
assumes that the sets are ordered using the comparison operator <. If some
other comparison operator has been used this needs to be passed to includes as
an extra (function object) argument after the other arguments.

 iter set_union(iter f1,iter l1,iter f2,iter l2,iter result).


This forms the union of the sets represented by the ranges [f1,l1] and [f2,l2].
The argument result is an output iterator that points at the start of the set that is
going to hold the union. The return value of the function is an output iterator
that points at the end of the new set.

The fact that the result argument is an output iterator means that you cannot use
set_union in the following, natural, fashion:

set<int, less<int> > s1, s2, s3;


// Add some elements to s1 and s2 ...
// Then form their union. (This does not work!)
set_union(s1.begin(), s1.end(),
s2.begin(), s2.end(),
s3.begin());

The reason is that begin() (also end()) when used with sets (or maps) returns a
(constant) input iterator. This type of iterator allows you to access elements of the set
for reading but not writing. (And this is a Good Thing since if you could assign to a
dereferenced iterator (as in (*i)= ...) then you could destroy the underlying order of
the set.)

The solution is to use an insert iterator based on the set type. This, basically, converts
an assignment (*i)=value (which is illegal) into a (legal) insertion s.insert(i,value)
(where s is the set object that the iterator i is pointing into). It is used as follows:

// Typedef for convenience.


typedef set<int, less<int> > intSet;
intSet s1, s2, s3;
// Add some elements to s1 and s2 ...
// Then form their union.
set_union(s1.begin(), s1.end(),
s2.begin(), s2.end(),
insert_iterator<intSet>(s3,s3.begin()) );

Here is an example illustrating all these operations.

<set-theory.cc>=
#include <iostream.h>
#include <set.h>
#include <algo.h>
#include <iterator.h>
#include printset.h

void main()
{
typedef set<int, less<int> > intSet;

intSet s1, s2, s3, s4;

for (int i=0; i<10; i++)


{ s1.insert(i);
s2.insert(i+4);
}
for (int i=0; i<5; i++) s3.insert(i);

cout << s1 = << s1 << endl;


cout << s2 = << s2 << endl;
cout << s3 = << s3 << endl;

// Is s1 a subset of s2?
bool test = includes(s2.begin(),s2.end(),s1.begin(),s1.end());
cout << s1 subset of s2 is << (test ? true. : false.) << endl;

// Is s3 a subset of s1?
test = includes(s1.begin(),s1.end(),s3.begin(),s3.end());
cout << s3 subset of s1 is << (test ? true. : false.) << endl;

// Form the union of s1 and s2.


set_union(s1.begin(), s1.end(), s2.begin(), s2.end(),
insert_iterator<intSet>(s4,s4.begin()) );
cout << s1 union s2 = << s4 << endl;

// Erase s4 and form intersection of s1 and s2. (If we don't erase


// s4 then we will get the previous contents of s4 as well).
s4.erase(s4.begin(),s4.end());
set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(),
insert_iterator<intSet>(s4,s4.begin()) );
cout << s1 intersection s2 = << s4 << endl;

// Now set difference.


s4.erase(s4.begin(),s4.end());
set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),
insert_iterator<intSet>(s4,s4.begin()) );
cout << s1 minus s2 = << s4 << endl;

// Set difference is not symmetric.


s4.erase(s4.begin(),s4.end());
set_difference(s2.begin(), s2.end(), s1.begin(), s1.end(),
insert_iterator<intSet>(s4,s4.begin()) );
cout << s2 minus s1 = << s4 << endl;

// Finally symmetric difference.


s4.erase(s4.begin(),s4.end());
set_symmetric_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),
insert_iterator<intSet>(s4,s4.begin()) );
cout << s1 symmetric_difference s2 = << s4 << endl;
// Which is symmetric!
s4.erase(s4.begin(),s4.end());
set_symmetric_difference(s2.begin(), s2.end(), s1.begin(), s1.end(),
insert_iterator<intSet>(s4,s4.begin()) );
cout << s2 symmetric_difference s1 = << s4 << endl;
}

23.8 Maps
See the section STL References

23.9 STL Algorithms


See the section STL References

24. Threads in C++


 IBM pthread User Guide, Thread concepts, API
reference http://www.as400.ibm.com/developer/threads/uguide/document.h
tm and mirror site is at IBM main site
 QpThread Library for C++ provides object oriented framework in C++ for
threads and Unix signals on top of system level threads (currently POSIX
Threads) http://lin.fsid.cvut.cz/~kra/index.html
 ThreadJack supports Java-like multi-thread programming model with platform
independent C++ class
library http://www.esm.co.jp/divisions/open-sys/ThreadJack/index-e.html and
here is the download-site
 APE is the "APE Portable Environment" and class libraries for writing portable
threaded servers in C++, under UNIX (pthread) and Win32 API's. APE provides
portable class abstraction for threads, sockets, file handling, and
synchronization objects. The goal of APE is to make writing threaded servers in
C++ both practical and convient, even for small and simple projects, and hence
simplicity and low runtime overhead are design
goalshttp://www.voxilla.org/projects/projape.html
 Portabale Thread Lib http://www.media.osaka-cu.ac.jp/~k-abe/PTL
 Thread-Recyling in C++ http://www.sigs.de/html/kuhlmann.html

24.1 Threads Tutorial


 You can download all the tutorials in one file from aldev-site
 Threads tutorial is
at http://www.math.arizona.edu/swig/pthreads/threads.html
 HERT tutorial at http://www.hert.org/docs/tutorials, go here to search for
"Threads".
 Intro to threads at linuxjournal
 North Arizona Univ NAU
 Posix threads Acctcom multi-thread

24.2 Designing a Thread Class in C++


This section is written by Ryan Teixeira and the document is located here .

Introduction

Multi threaded programming is becomming ever more popular. This section presents a
design for a C++ class that will encapsulate the threading mechanism. Certain aspects
of thread programming, like mutexes and semaphores are not discussed here. Also,
operating system calls to manipulate threads are shown in a generic form.

Brief Introduction To Threads

To understand threads one must think of several programs running at once. Imagine
further that all these programs have access to the same set of global variables and
function calls. Each of these programs would represent a thread of execution and is
thus called a thread. The important differentiation is that each thread does not have to
wait for any other thread to proceed. All the threads proceed simultaneously. To use a
metaphor, they are like runners in a race, no runner waits for another runner. They all
proceed at their own rate.

Why use threads you might ask. Well threads can often improve the performance of
an application and they do not incur significant overhead to implement. They
effectively give good bang for a buck. Imagine an image server program that must
service requests for images. The program gets a request for an image from another
program. It must then retieve the image from a database and send it to the program
that requested it. If the server were implemented in a single threaded approach, only
one program could request at a time. When it was busy retrieving an image and
sending it to a requestor, it could not service other requests. Of course one could still
implement such a system without using threads. It would be a challenge though.
Using threads, one can very naturally design a system to handle multiple requests. A
simple approach would be to create a thread for each request received. The main
thread would create this thread upon receipt of a request. The thread would then be
responsible for the conversation with the client program from that point on. After
retrieving the image, the thread would terminate itself. This would provide a smooth
system that would continue to service requests even though it was busy serviceing
other requests at the same time.

Basic Approach

The create a thread, you must specify a function that will become the entry point for
the thread. At the operating system level, this is a normal function. We have to do a
few tricks to wrap a C++ class around it because the entry function cannot be a
normal member function of a class. However, it can be a static member function of a
class. This is what we will use as the entry point. There is a gotcha here though. Static
member functions do not have access to the this pointer of a C++ object. They can
only access static data. Fortunately, there is way to do it. Thread entry point functions
take a void * as a parameter so that the caller can typecast any data and pass in to the
thread. We will use this to pass this to the static function. The static function will then
typecast the void * and use it to call a non static member function.

The Implementation

It should be mentioned that we are going to discuss a thread class with limited
functionality. It is possible to do more with threads than this class will allow.

class Thread
{
public:
Thread();
int Start(void * arg);
protected:
int Run(void * arg);
static void * EntryPoint(void*);
virtual void Setup();
virtual void Execute(void*);
void * Arg() const {return Arg_;}
void Arg(void* a){Arg_ = a;}
private:
THREADID ThreadId_;
void * Arg_;

};

Thread::Thread() {}

int Thread::Start(void * arg)


{
Arg(arg); // store user data
int code = thread_create(Thread::EntryPoint, this, & ThreadId_);
return code;
}

int Thread::Run(void * arg)


{
Setup();
Execute( arg );
}

/*static */
void * Thread::EntryPoint(void * pthis)
{
Thread * pt = (Thread*)pthis;
pthis->Run( Arg() );
}

virtual void Thread::Setup()


{
// Do any setup here
}

virtual void Thread::Execute(void* arg)


{
// Your code goes here
}

It is important to understand that we are wrapping a C++ object around a thread. Each
object will provide an interface to a single thread. The thread and the object are not
the same. The object can exist without a thread. In this implementation, the thread
does not actually exist until the Start function is called.

Notice that we store the user argument in the class. This is necessary because we need
a place to store it temporarily until the thread is started. The operating system thread
call allows us to pass an argument but we have used it to pass the this pointer. So we
store the real user argument in the class itself and when the execute function is called
it can get access to the argument.

Thread(); This is the constructor.

int Start(void * arg); This function provides the means to create the thread and start
it going. The argument arg provides a way for user data to be passed into the thread.
Start() creates the thread by calling the operating system thread creation function.

int Run(void * arg); This is a protected function that should never be tampered with.

static void * EntryPoint(void * pthis); This function serves as the entry point to the
thread. It simply casts pthis to Thread * and
virtual void Setup(); This function is called after the thread has been created but
before Execute() is called. If you override this function, remember to call the parent
class Execute().

virtual void Execute(void *); You must override this function to provide your own
functionality.

Using The Thread Class

To use the thread class, you derive a new class. you override the Execute() function
where you provide your own functionality. You may override the Setup() function to
do any start up duties before Execute is called. If you override Setup(), remember to
call the parent class Setup().

Conclusion

This section presented an implementation of a thread class written in C++. Of course


it is a simple approach but it provides a sound foundation upon which to build a more
robust design.

If you have comments or suggestions, email to Ryan Teixeira

25. C++ Utilities


Visit the following sites for C++ Utilities

 C++ Binary File


I/O http://www.angelfire.com/country/aldev0/cpphowto/cpp_BinaryFileIO.ht
ml and at mirror site
 Portability
Guide http://www.angelfire.com/country/aldev0/cpphowto/cpp_PortabilityG
uide.html and at mirror site
 Snippets collections of C++
routines http://www.angelfire.com/country/aldev0/cpphowto/cpp_Snippets.
html and at mirror site and at snippets site
 escape ISB for C++ - Provides information on how to develop and program
distributed, object-based applications in C++ for Windows and Unix using the
Netscape Internet Service
Broker http://docs.iplanet.com/docs/manuals/enterprise/cpluspg/contents.ht
m
 Common c++ http://www.voxilla.org/projects/projape.html
 Large List of free C++
libs http://www.thefreecountry.com/developercity/freelib.html
 C++ Tools http://development.freeservers.com
 C++ Tools CUJ http://www.cuj.com/code
 C++libs Univ of vaasa http://garbo.uwasa.fi/pc/c-lang.html

26. Other Formats of this Document


This document is published in 14 different formats namely - DVI, Postscript, Latex,
Adobe Acrobat PDF, LyX, GNU-info, HTML, RTF(Rich Text Format), Plain-text,
Unix man pages, single HTML file, SGML (Linuxdoc format), SGML (Docbook
format), MS WinHelp format.

This howto document is located at -

 http://www.linuxdoc.org and click on HOWTOs and search for howto


document name using CTRL+f or ALT+f within the web-browser.

You can also find this document at the following mirrors sites -

 http://www.caldera.com/LDP/HOWTO
 http://www.linux.ucla.edu/LDP
 http://www.cc.gatech.edu/linux/LDP
 http://www.redhat.com/mirrors/LDP
 Other mirror sites near you (network-address-wise) can be found
at http://www.linuxdoc.org/mirrors.html select a site and go to directory
/LDP/HOWTO/xxxxx-HOWTO.html

 You can get this HOWTO document as a single file tar ball in HTML, DVI,
Postscript or SGML formats from
-ftp://www.linuxdoc.org/pub/Linux/docs/HOWTO/other-formats/ and http://
www.linuxdoc.org/docs.html#howto
 Plain text format is
in: ftp://www.linuxdoc.org/pub/Linux/docs/HOWTO and http://www.linuxdoc
.org/docs.html#howto
 Single HTML file format is in: http://www.linuxdoc.org/docs.html#howto

Single HTML file can be created with command (see man sgml2html) -
sgml2html -split 0 xxxxhowto.sgml
 Translations to other languages like French, German, Spanish, Chinese,
Japanese are
in ftp://www.linuxdoc.org/pub/Linux/docs/HOWTO andhttp://www.linuxdoc.
org/docs.html#howto Any help from you to translate to other languages is
welcome.

The document is written using a tool called "SGML-Tools" which can be got from
- http://www.sgmltools.org Compiling the source you will get the following
commands like

 sgml2html xxxxhowto.sgml (to generate html file)


 sgml2html -split 0 xxxxhowto.sgml (to generate a single page html file)
 sgml2rtf xxxxhowto.sgml (to generate RTF file)
 sgml2latex xxxxhowto.sgml (to generate latex file)

26.1 Acrobat PDF format


PDF file can be generated from postscript file using either
acrobat distill or Ghostscript. And postscript file is generated from DVI which in
turn is generated from LaTex file. You can download distill software
from http://www.adobe.com. Given below is a sample session:

bash$ man sgml2latex


bash$ sgml2latex filename.sgml
bash$ man dvips
bash$ dvips -o filename.ps filename.dvi
bash$ distill filename.ps
bash$ man ghostscript
bash$ man ps2pdf
bash$ ps2pdf input.ps output.pdf
bash$ acroread output.pdf &

Or you can use Ghostscript command ps2pdf. ps2pdf is a work-alike for nearly all the
functionality of Adobe's Acrobat Distiller product: it converts PostScript files to
Portable Document Format (PDF) files. ps2pdf is implemented as a very small
command script (batch file) that invokes Ghostscript, selecting a special "output
device" called pdfwrite. In order to use ps2pdf, the pdfwrite device must be included
in the makefile when Ghostscript was compiled; see the documentation on building
Ghostscript for details.
26.2 Convert Linuxdoc to Docbook format
This document is written in linuxdoc SGML format. The Docbook SGML format
supercedes the linuxdoc format and has lot more features than linuxdoc. The linuxdoc
is very simple and is easy to use. To convert linuxdoc SGML file to Docbook SGML
use the program ld2db.sh and some perl scripts. The ld2db output is not 100% clean
and you need to use the clean_ld2db.pl perl script. You may need to manually correct
few lines in the document.

 Download ld2db program


from http://www.dcs.gla.ac.uk/~rrt/docbook.html or from Al Dev site
 Download the cleanup_ld2db.pl perl script from from Al Dev site

The ld2db.sh is not 100% clean, you will get lots of errors when you run

bash$ ld2db.sh file-linuxdoc.sgml db.sgml


bash$ cleanup.pl db.sgml > db_clean.sgml
bash$ gvim db_clean.sgml
bash$ docbook2html db.sgml

And you may have to manually edit some of the minor errors after running the perl
script. For e.g. you may need to put closing tag < /Para> for each < Listitem>

26.3 Convert to MS WinHelp format


You can convert the SGML howto document to Microsoft Windows Help file, first
convert the sgml to html using:

bash$ sgml2html xxxxhowto.sgml (to generate html file)


bash$ sgml2html -split 0 xxxxhowto.sgml (to generate a single page
html file)

Then use the tool HtmlToHlp. You can also use sgml2rtf and then use the RTF files for
generating winhelp files.

26.4 Reading various formats


In order to view the document in dvi format, use the xdvi program. The xdvi program
is located in tetex-xdvi*.rpm package in Redhat Linux which can be located through
ControlPanel | Applications | Publishing | TeX menu buttons. To read dvi document
give the command -
xdvi -geometry 80x90 howto.dvi
man xdvi
And resize the window with mouse. To navigate use Arrow keys, Page Up, Page
Down keys, also you can use 'f', 'd', 'u', 'c', 'l', 'r', 'p', 'n' letter keys to move up, down,
center, next page, previous page etc. To turn off expert menu press 'x'.

You can read postscript file using the program 'gv' (ghostview) or 'ghostscript'. The
ghostscript program is in ghostscript*.rpm package and gv program is in gv*.rpm
package in Redhat Linux which can be located through ControlPanel | Applications |
Graphics menu buttons. The gv program is much more user friendly than ghostscript.
Also ghostscript and gv are available on other platforms like OS/2, Windows 95 and
NT, you view this document even on those platforms.

 Get ghostscript for Windows 95, OS/2, and for all OSes
from http://www.cs.wisc.edu/~ghost

To read postscript document give the command -


gv howto.ps
ghostscript howto.ps

You can read HTML format document using Netscape Navigator, Microsoft Internet
explorer, Redhat Baron Web browser or any of the 10 other web browsers.

You can read the latex, LyX output using LyX a X-Windows front end to latex.

27. Translations To Other Languages


 Translation to Polish is
at http://strony.wp.pl/wp/chq/c/howto/node1.html thanks to Darek
Ostolski Darek Ostolski
 Translations to other languages like French, German, Spanish, Chinese,
Japanese are
in ftp://www.linuxdoc.org/pub/Linux/docs/HOWTO andhttp://www.linuxdoc.
org/docs.html#howto

Any help from you to translate to other languages is welcome.


28. Copyright
Copyright policy is GNU/GPL as per LDP (Linux Documentation project). LDP is a
GNU/GPL project. Additional requests are that you retain the author's name, email
address and this copyright notice on all the copies. If you make any changes or
additions to this document then you please intimate all the authors of this document.
Brand names mentioned in this document are property of their respective owners.

29. Appendix A String Program Files


You can download all programs as a single tar.gz file from Download String and
give the following command to unpack

bash$ man tar


bash$ tar ztvf C++Programming-HOWTO.tar.gz
This will list the table of contents

bash$ tar zxvf C++Programming-HOWTO.tar.gz


This will extract the files

 Read the header file first and then see the example cpp program
o String.h http://www.angelfire.com/country/aldev0/cpphowto/String.h
o StringBuffer.h http://www.angelfire.com/country/aldev0/cpphowto/
StringBuffer.h
o StringTokenizer.h http://www.angelfire.com/country/aldev0/
cpphowto/StringTokenizer.h
o StringRW.h http://www.angelfire.com/country/aldev0/cpphowto/
StringRW.h
o string_multi.h http://www.angelfire.com/country/aldev0/cpphowto/
string_multi.h
o example_String.cpp http://www.angelfire.com/country/aldev0/
cpphowto/example_String.cpp
 File manipulation class, only length() function is implemented..
o File.h http://www.angelfire.com/country/aldev0/cpphowto/File.h
o File.cpp http://www.angelfire.com/country/aldev0/cpphowto/File.cpp
 The zap() implemented here ..
o my_malloc.h http://www.angelfire.com/country/aldev0/cpphowto/
my_malloc.h
o my_malloc.cpp http://www.angelfire.com/country/aldev0/
cpphowto/my_malloc.cpp
 Implementation of string class...
o String.cpp http://www.angelfire.com/country/aldev0/cpphowto/
String.cpp
o StringTokenizer.cpp http://www.angelfire.com/country/aldev0/
cpphowto/StringTokenizer.cpp
o StringBuffer.cpp http://www.angelfire.com/country/aldev0/
cpphowto/StringBuffer.cpp
o StringRW.cpp http://www.angelfire.com/country/aldev0/cpphowto/
StringRW.cpp
 Debug facilities ..
o debug.h http://www.angelfire.com/country/aldev0/cpphowto/debug.h
o debug.cpp http://www.angelfire.com/country/aldev0/cpphowto/
debug.cpp
o Makefile http://www.angelfire.com/country/aldev0/cpphowto/
Makefile
 Sample java file for testing the functionalities of String class ..
o string.java http://www.angelfire.com/country/aldev0/cpphowto/
string.java

You might also like