Sei sulla pagina 1di 81

GE2155 COMPUTER PRACTICE LABORATORY II L T P C

0 1 2 2
SYLLABUS
1. UNIX COMMANDS 15
Study of Unix OS - Basic Shell Commands - Unix Editor
2. SHELL PROGRAMMING 15
Simple Shell program - Conditional Statements - Testing and Loops
3. C PROGRAMMING ON UNIX 15
Dynamic Storage Allocation-Pointers-Functions-File Handling
TOTAL : 45 PERIODS
TABLE OF CONTENTS
Ex. No Lab # Name of the experiment Page No
1 BASIC UNIXCOMMANDS
1.1 1 STUDY OF UNIX OS
UNIX FEATURES
SHELL-KERNEL ARCHITECTURE
FILE SYSTEM
1.2 2 UNIX COMMANDS
GENERAL COMMANDS
DIRECTORY COMMANDS
FILE COMMANDS
1.3 3 VI EDITOR
INSERT MODE
COMMANDMODE
EX MODE
1.4 4 FILTER COMMANDS
HEAD/TAIL
CUT/PASTE
SORT
1.5 5 REGULAR EXPRESSION
GREP
EGREP
2 SHELL PROGRAMMING
2.1 6 SIMPLE SHELL PROGRAMS
A SWAPPING TWOVALUES
B CENTIGRADE TOFAHRENHEIT
C AREA OF A CIRCLE
D SIMPLE INTEREST
2.2 7 DECISION MAKING
A ODD OR EVEN
B BIGGEST OF 3NUMBERS
C LEAP YEAR
Ex. No Lab # Name of the experiment Page No
D GRADE DETERMINATION
E EMPLOYEE PAY
F STRINGCOMPARISON
2.3 8 MULTI-WAY BRANCHING
A VOWEL OR CONSONANT
B SIMPLE CALCULATOR
C RENTAL OPTIONS
D VOTE ELIGIBILITY
2.4 9 LOOPING CONSTRUCTS
A MULTIPLICATIONTABLE
B ARMSTRONGNUMBER
C NUMBER REVERSE
D FIBONACCI SERIES
E PRIME NUMBER
F FACTORIAL VALUE
G SUM OF 1+2+3+N
H DATA STATISTICS
2.5 10 COMMAND BASED SCRIPTS
A TIME BASEDGREET
B MONTH DAYS
C COMMANDMENU
D DIRECTORY LISTING
E FILE TYPE
F FILE DUPLICATES
G DETECT USER LOGON
H COMPILE &EXECUTE
3 CPROGRAMMING
3.1 11 INTRODUCTION TO POINTERS
A REFERENCE &DEREFERENCE
B POINTER VARIABLES
C POINTER TOPOINTER
D ADDITION USINGPOINTERS
Ex. No Lab # Name of the experiment Page No
E BASIC CALCULATOR
3.2 12 POINTER PROGRAMMING
A PASS BY VALUE / REFERENCE
B RETURN BY REFERENCE
C SUM OF ARRAY ELEMENTS
D PRINTING2DARRAY
E STRINGCOPY
F STUDENT DETAILS
G PAYROLL PROCESSING
3.3 13 DYNAMIC MEMORY ALLOCATION
A MARK AGGREGATE
B STRINGREALLOCATION
C 2DARRAY ALLOCATION
3.4 14 FILE HANDLING
A WRITE TOFILECHARACTER I/O
B FILE STATISTICS
C EMPLOYEE FILERANDOM ACCESS
3.5 15 COMMAND LINE ARGUMENTS
A ARGUMENT LIST
B FILE COPYCP
C FILE DISPLAYCAT
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 1.1 STUDY OF UNIXOPERATINGSYSTEM
AIM
To introduce the concept of UNIX Operating System
OPERATING SYSTEM
An Operating System is a set of programs that
Functions as an virtual machine by presenting an interface that is easier to program
than the underlying hardware
Acts as resource management through orderly and controlled allocation of the
processors, memories, and I/O devices among the programs competing for it.
OS TYPES
1. Single UserThe system will have its own hard disk, memory, CPU and other
resources all dedicated to a single user. Eg. MS-DOS
2. Multi UserThe users having access to a multi-user system will have just a terminal
and a keyboard. The other resources such as hard disk, printers are centrally located.
The user is expected to simply hook onto his account, perform the work, disconnect
and leave quietly. Eg. UNIX
UNIXHISTORY
The spade work for UNIX began at AT&T Bell Laboratories in 1969 by Ken Thompson and
Dennis Ritchie. The OS was initially known as UNICS (jokingly UNiplexed Information and
Computing System). In 1970 UNICS finally became UNIX. In 1973, UNIX was rewritten in
1973 in C principally authored by Ritchie.
UNIX FEATURES
1. Multi-user systemMulti-user capability of UNIX allows several users to use the
same computer to perform their tasks. Several terminals [Keyboards and Monitors]
are connected to a single powerful computer [UNIX server] and each user can work
with their terminals.
2. Multi-tasking systemMultitasking is the capability of the operating system to
perform various task simultaneously, i.e. a user can run multiple tasks concurrently.
3. Programming FacilityUNIX is highly programmable, the UNIX shell has all the
necessary ingredients like conditional and control structures, etc.
4. SecurityUNIX allows sharing of data; every user must have a single login name
and password. So, accessing another users data is impossible without his permission.
5. PortabilityUNIX is portable because it is written in a high level language. So,
UNIX can be run on different computers.
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
6. CommunicationUNIX supports communication between different terminals of the
same server as well as between terminals on different servers.
Apart from these features, UNIX has an extensive Tool kit, exhaustive system calls and
Libraries and enhanced GUI (X Window).
ORGANIZATION OF UNIX
The UNIX system is functionally organized at three levels and are:
1. Thekernel, which schedules tasks and manages storage;
2. Theshell, which connects and interprets users' commands, calls programs from
memory, and executes them; and
3. Thetools and applications that offer additional functionality to the OS
UNIX Structure
The kernel is the heart of the system, a collection of programs written in C that directly
communicate with the hardware. There is only one kernel for any system. It's that part of
UNIX system that is loaded into memory when the system is booted. It manages the system
resources, allocates time between user and processes, decides process priorities, and performs
all other tasks. The kernel, in traditional parlance, is often called the Operating system.
The shell, on the other hand, is the "sleeping beauty" of UNIX. It is actually the interface
between the user and the kernel. The shell is the agency which takes care of the features of
redirection and has a programming capability of its own.
The Tools and Applications consist of Application Software, Compilers, Database Package,
Internet tools, UNIX commands, etc.
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
FILESYSTEM
A file in UNIX is nothing but a storehouse of information and everything is treated as a file
by UNIX. The files can be broadly classified as follows:
Ordinary filesContains stream of data. All data, text, source programs, object and
executable code, commands fall into this category.
Directory filesContains no external data. It contains an entry, name of the file and
its inode (identification number) for each file and subdirectory under that directory.
Directory files are not created by the user but by the UNIX system itself.
Device filesEven physical devices are treated as files. These are special in the sense
that any output directed to it will be reflected onto the respective device.
UNIX File System
All files in UNIX are related to one another. The file system of UNIX resembles a tree that
grows from top to bottom as shown in the figure. The file system begins with a directory
called root (at the top). The root directory is denoted by a slash (\). Branching from root there
are several directories such as bin, lib, etc, tmp, dev. Each of these directories contains
several sub-directories and files.
Result
Thus the study of UNIX Operating System has been completed successfully.
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 1.2 BASIC COMMANDS
Aim
To study and execute Unix commands.
Unix is security conscious, and can be used only by those persons who have an account.
Telnet (Telephone Network) is a Terminal emulator program for TCP/IP networks that
enables users to log on to remote servers.
Tologon, typetelnet server_ipaddress inrun window.
User has to authenticate himself by providing username and password. Once verified, a
greeting and $ prompt appears. The shell is now ready to receive commands from the user.
Options suffixed with a hyphen () and arguments are separated by space.
General commands
Command Function
dat e Used to display the current system date and time.
dat e +%D Displays date only
dat e +%T Displays time only
dat e +%Y Displays the year part of date
dat e +%H Displays the hour part of time
cal Calendar of the current month
cal year Displays calendar for all months of the specified year
cal month year Displays calendar for the specified month of the year
who Login details of all users such as their IP, Terminal No, User name,
who ami Used to display the login details of the user
t t y Used to display the terminal name
uname Displays the Operating System
uname r Shows version number of the OS (kernel).
uname n Displays domain name of the server
echo "txt" Displays the given text on the screen
echo $HOME Displays the user's home directory
bc Basic calculator. PressCtrl+d to quit
l p file Allows the user to spool a job along with others in a print queue.
man cmdname Manual for the given command. Pressq to exit
hi st or y To display the commands used by the user since log on.
exi t Exit from a process. If shell is the only process then logs out
Directory commands
Command Function
pwd Path of the present working directory
mkdi r dir A directory is created in the given name under the current directory
mkdi r dir1 dir2 A number of sub-directories can be created under one stroke
cd subdir Change Directory. If the subdir starts with / then path starts from
root (absolute) otherwise from current working directory.
cd To switch to the home directory.
cd / To switch to the root directory.
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Command Function
cd . . To move back to the parent directory
r mdi r subdir Removes an empty sub-directory.
File commands
Command Function
cat >filename To create a file with some contents. To end typing press Ctrl+d.
The> symbol means redirecting output to a file. (< for input)
cat filename Displays the file contents.
cat >>filename Used to append contents to a file
cp src des Copy files to given location. If already exists, it will be overwritten
cp i src des Warns the user prior to overwriting the destination file
cp r src des Copies the entire directory, all its sub-directories and files.
mv old new To rename an existing file or directory. i option can also be used
mv f1 f2 f3 dir To move a group of files to a directory.
mv v old new Display name of each file as it is moved.
r mfile Used to delete a file or group of files. i option can also be used
r m* To delete all the files in the directory.
r mr * Deletes all files and sub-directories
r mf * To forcibly remove even write-protected files
l s Lists all files and subdirectories (blue colored) in sorted manner.
l s name To check whether a file or directory exists.
l s name* Short-hand notation to list out filenames of a specific pattern.
l s a Lists all files including hidden files (files beginning with.)
l s x dirname To have specific listing of a directory.
l s R Recursive listing of all files in the subdirectories
l s l Long listing showing file access rights (read/write/execute-rwx for
user/group/others-ugo).
cmp file1 file2 Used to compare two files. Displays nothing if files are identical.
wc file It produces a statistics of lines (l), words(w), and characters(c).
chmod perm file Changes permission for the specified file. (r =4, w=2, x=1)
chmod 740 file sets all rights for user, read only for groups
and no rights for others
The commands can be combined using the pipeline (| ) operator. For example, number of
users logged in can be obtained as.
who | wc - l
Finally to terminate the unix session execute the commandexit or logout.
Result
Thus the study and execution of Unix commands has been completed successfully.
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
[ vi j ai @l ocal host vi j ai ] $ date
Sat Apr 9 13: 03: 47 I ST 2011
[ vi j ai @l ocal host vi j ai ] $ date +%D
04/ 09/ 11
[ vi j ai @l ocal host vi j ai ] $ date +%T
13: 05: 33
[ vi j ai @l ocal host vi j ai ] $ date +%Y
2011
[ vi j ai @l ocal host vi j ai ] $ date +%H
13
[ vi j ai @l ocal host vi j ai ] $ cal
Apr i l 2011
Su Mo Tu We Th Fr Sa
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
[ vi j ai @l ocal host vi j ai ] $ cal 08 1998
August 1998
Su Mo Tu We Th Fr Sa
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
[ vi j ai @l ocal host vi j ai ] $ cal 1800
1800
J anuar y Febr uar y Mar ch
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 1 1
5 6 7 8 9 10 11 2 3 4 5 6 7 8 2 3 4 5 6 7 8
12 13 14 15 16 17 18 9 10 11 12 13 14 15 9 10 11 12 13 14 15
19 20 21 22 23 24 25 16 17 18 19 20 21 22 16 17 18 19 20 21 22
26 27 28 29 30 31 23 24 25 26 27 28 23 24 25 26 27 28 29
30 31

Oct ober November December
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 1 1 2 3 4 5 6
5 6 7 8 9 10 11 2 3 4 5 6 7 8 7 8 9 10 11 12 13
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
12 13 14 15 16 17 18 9 10 11 12 13 14 15 14 15 16 17 18 19 20
19 20 21 22 23 24 25 16 17 18 19 20 21 22 21 22 23 24 25 26 27
26 27 28 29 30 31 23 24 25 26 27 28 29 28 29 30 31
30
[ vi j ai @l ocal host vi j ai ] $ who
r oot : 0 Apr 9 08: 41
vi j ai pt s/ 0 Apr 9 13: 00 ( scl - 64)
cse1 pt s/ 3 Apr 9 13: 18 ( scl - 41. smkf omr a. com)
ecea pt s/ 4 Apr 9 13: 18 ( scl - 29. smkf omr a. com)
[ vi j ai @l ocal host vi j ai ] $ who am i
vi j ai pt s/ 0 Apr 9 13: 00 ( scl - 64)
[ vi j ai @l ocal host vi j ai ] $ tty
/ dev/ pt s/ 0
[ vi j ai @l ocal host vi j ai ] $ uname
Li nux
[ vi j ai @l ocal host vi j ai ] $ uname -r
2. 4. 20- 8smp
[ vi j ai @l ocal host vi j ai ] $ uname -n
l ocal host . l ocal domai n
[ vi j ai @l ocal host vi j ai ] $ echo "How are you"
How ar e you
[ vi j ai @l ocal host vi j ai ] $ echo $HOME
/ home/ vi j ai
[ vi j ai @l ocal host vi j ai ] $ echo $USER
vi j ai
[ vi j ai @l ocal host vi j ai ] $ bc
bc 1. 06
Copyr i ght 1991- 1994, 1997, 1998, 2000 Fr ee Sof t war e Foundat i on, I nc.
3+5
8
2%3
2
[ vi j ai @l ocal host l oops] $ pwd
/ home/ vi j ai / shel l scr i pt s/ l oops
[ vi j ai @l ocal host vi j ai ] $ mkdir filter
[ vi j ai @l ocal host vi j ai ] $ ls
f i l t er l i st . sh r egexpr shel l scr i pt s
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
[ vi j ai @l ocal host vi j ai ] $ cd shellscripts/loops/
[ vi j ai @l ocal host l oops] $
[ vi j ai @l ocal host l oops] $ cd
[ vi j ai @l ocal host vi j ai ] $
[ vi j ai @l ocal host l oops] $ cd /
[ vi j ai @l ocal host / ] $
[ vi j ai @l ocal host / ] $ cd /home/vijai/shellscripts/loops/
[ vi j ai @l ocal host l oops] $ cd ..
[ vi j ai @l ocal host shel l scr i pt s] $
[ vi j ai @l ocal host vi j ai ] $ rmdir filter
[ vi j ai @l ocal host vi j ai ] $ ls
l i st . sh r egexpr shel l scr i pt s
[ vi j ai @l ocal host vi j ai ] $ cat > greet
hi ece- a
wi shi ng u t he best
[ vi j ai @l ocal host vi j ai ] $ cat greet
hi ece- a
wi shi ng u t he best
[ vi j ai @l ocal host vi j ai ] $ cat >> greet
bye
[ vi j ai @l ocal host vi j ai ] $ cat greet
hi ece- a
wi shi ng u t he best
bye
[ vi j ai @l ocal host vi j ai ] $ ls
gr eet l i st . sh r egexpr shel l scr i pt s
[ vi j ai @l ocal host vi j ai ] $ ls -a
. . bash_l ogout . canna . gt kr c r egexpr . vi mi nf o. t mp
. . . bash_pr of i l e . emacs . kde shel l scr i pt s . xemacs
. bash_hi st or y . bashr c gr eet l i st . sh . vi mi nf o
[ vi j ai @l ocal host vi j ai ] $ ls -l
t ot al 16
- r w- r w- r - - 1 vi j ai vi j ai 32 Apr 11 14: 52 gr eet
- r w- r w- r - - 1 vi j ai vi j ai 30 Apr 4 13: 58 l i st . sh
dr wxr wxr - x 2 vi j ai vi j ai 4096 Apr 9 14: 30 r egexpr
dr wxr wxr - x 7 vi j ai vi j ai 4096 Apr 4 14: 57 shel l scr i pt s
[ vi j ai @l ocal host vi j ai ] $ cp greet ./regexpr/
[ vi j ai @l ocal host vi j ai ] $ ls
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
gr eet l i st . sh r egexpr shel l scr i pt s
[ vi j ai @l ocal host vi j ai ] $ ls ./regexpr
demo gr eet
[ vi j ai @l ocal host vi j ai ] $ cp -i greet ./regexpr/
cp: over wr i t e ' gr eet ' ? n
[ vi j ai @l ocal host vi j ai ] $ mv greet greet.txt
[ vi j ai @l ocal host vi j ai ] $ ls
gr eet . t xt l i st . sh r egexpr shel l scr i pt s
[ vi j ai @l ocal host vi j ai ] $ mv greet.txt ./regexpr/
[ vi j ai @l ocal host vi j ai ] $ ls
l i st . sh r egexpr shel l scr i pt s
[ vi j ai @l ocal host vi j ai ] $ ls ./regexpr/
demo gr eet . t xt
[ vi j ai @l ocal host vi j ai ] $ ls
f act . sh l i st . sh pr i me. sh r egexpr shel l scr i pt s
[ vi j ai @l ocal host vi j ai ] $ rm -i *.sh
r m: r emove r egul ar f i l e ' f act . sh' ? y
r m: r emove r egul ar f i l e ' l i st . sh' ? n
r m: r emove r egul ar f i l e ' pr i me. sh' ? y
[ vi j ai @l ocal host vi j ai ] $ ls
l i st . sh r egexpr shel l scr i pt s
[ vi j ai @l ocal host vi j ai ] $ wc list.sh
4 9 30 l i st . sh
[ vi j ai @l ocal host vi j ai ] $ wc -l list.sh
4 l i st . sh
[ vi j ai @l ocal host vi j ai ] $ cmp list.sh fact.sh
l i st . sh f act . sh di f f er : byt e 1, l i ne 1
[ vi j ai @l ocal host vi j ai ] $ ls -l list.sh
- r w- r w- r - - 1 vi j ai vi j ai 30 Apr 4 13: 58 l i st . sh
[ vi j ai @l ocal host vi j ai ] $ chmod ug+x list.sh
[ vi j ai @l ocal host vi j ai ] $ ls -l list.sh
- r wxr wxr - - 1 vi j ai vi j ai 30 Apr 4 13: 58 l i st . sh
[ vi j ai @l ocal host vi j ai ] $ chmod 740 list.sh
[ vi j ai @l ocal host vi j ai ] $ ls -l list.sh
- r wxr - - - - - 1 vi j ai vi j ai 30 Apr 4 13: 58 l i st . sh
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 1.3 STUDY OF VI EDITOR
Aim
To introduce the concept of text editingvi editor and the options regarding the control
of the editor.
vi Editor
A text editor is one of the most common and useful tools in all Operating Systems.
Unix provides a versatile editor vi, a full-screen editor and owes its origin to Bill J oy. "vi"
stands for visual editor. A vi session begins by invoking vi with or without a filename
$vi
$vi filename
The user is presented with a full empty screen, each line beginning with a ~. This is vi's way
of indicating non-existent lines. Out of 25 lines on the terminal, 24 can be used to enter text.
The last line is reserved for commands and also used by the system to display messages. vi
functions in three modes namely:
1. Input modeWhere any key depressed is entered as text
2. Command modeWhere keys are used as commands to act on text (initial mode)
3. ex modeex mode commands that can be entered in the last line to act on text
vi modes
INPUT MODE
vi starts with command mode. To insert text any of the following commands should be used.
Commands Function
i Inserts text to the left of the cursor.
I Inserts text at the beginning of line.
a Appends text to right of cursor
A Appends text at end of line
o Opens line below
O Opens line above
InInput mode the editor displaysINSERT in the last line. PressEnter key to start a fresh line
of text in Input mode and the ~disappears. To quit input mode pressEsc key.
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
COMMAND MODE
EDIT COMMANDS
Command Function
R Replaces more than a single character. The editor displays REPLACE in
the last line. The existing text is overwritten as they are typed.
s Deletes a single character to the left and switches toInput mode.
x Deletes the character in the current cursor position
?text Locates thetext in the file. If not found, the message "Pattern not found"
appears. Usen to repeat the forward search andN for backward search.
U or u Reverses the last change made to the buffer.
dd Cuts the entire line
dw Cuts the entire word
d$ Cuts a line from cursor position to the end of the line
d0 Cuts from the cursor position to the start of the line
yy Copies (yanks) the entire line
yw Copies the entire word
p Pastes the text
NAVIGATION COMMANDS
Command Function
b Moves back to beginning of a word
w Moves forward to beginning of word
| Moves to start of the line
$ Moves to end of the line
k Up one line
j Down one line
h Left one character
l Right one character
Ct r l +f Scrolls a page forward
Ct r l +b Scrollsapage backward
lG To move to the specific line
One of the most notable features of vi is the facility of prefixing a number to most
commands. When prefixed, commands interpret the instruction to be repeated as many times.
For example3x deletes the next three character.
THE EX MODE
The essential save and exit commands form the features of ex mode. Press : (colon) in
command mode to switch to ex mode. The: is displayed in the last line. Type the command
and pressEnter key to execute the same.
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Command Function
w Saves file, displays the number of lines & characters and returns to
Input mode. If it is an unnamed file then vi puts a message.
w file The file is saved under the given name
L1,L2 wfile Used to write specific line numbers to some file. The. (dot) represents
current line, 0 for first line and$ could be used to represent last line.
q Quits vi session and returns to $ prompt. vi has a safety mechanism
that warns if changes made to file are not saved.
q! Quits vi session without saving any changes made since the last save
wq Save and exit
sh Escape to shell
%s/ Sstr/ Rstr/ g This is yet another powerful feature known as substitution. It is
similar to Find and Replace. % represents all lines, g makes it global.
To make vi ask for confirmation before replacing usegc instead of g.
r file To insert another file into the current file.
new file Splits screen into multiple windows and opens the file.
vi editor
vi Editor
Result
Thus the study of text manipulation using vi editor has been completed successfully.
This is vi improved vim
A rudimentary text
~
~
~
~
~
~
~
~
~
Sample.txt 2L, 30C written
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 1.4 Simple Filters
Aim
To query a data file using filter commands in unix.
Filters are the central commands of the UNIX tool kit. It acts on data file where lines are
records, fields delimited by a character not used by the data (mostly |, default is white space).
The output is a set of records and the input file is unaltered by these commands.
Command Function
headused to display the first few records (10 records by default)
head st ud Displaysfirst 10 recordsby default
head - 5 st ud Displays first 5 records
head - 1 st ud | wc c length of first record
tailused to display the last few records (10 records by default)
t ai l st ud Displays last 10 records by default
t ai l - 5 st ud | t ee l ast 5 Last 5recordslisted & storedinfilelast5 usingtee
cutused to extract specific fields. The d option specifies the delimiter and f for
specifying the field list. Thec option may be used if extraction is done character wise
cut d \ | - f 1, 3, 4 st ud Fields 1,3,4 listed
cut d \ | - f 2- 4 st ud Fields 2,3,4 listed
past e d \ | l i st 1 l i st 2 merges two cut fileslist1 andlist2
sortreorders the file as per ASCII sequence. Thet option is used to specify delimiter and
k option to specify the field
sor t st ud Sorted on 1
st
column by default
sor t t \ | - k 3 st ud Sort as per 3
rd
column
sor t c st ud Check if file is sorted usingc option
sor t - t \ | - k 4, 4 - k 3, 3
st ud
Sorting on secondary keys
sor t - t \ | - nr k 4 st ud Sort on numeric field usingn option, r for reverse
uni q st ud Display unique entriesin a sorted file
trtranslates characters. Can be used to change text case. It works with standard input <
t r ' [ a- z] ' ' [ A- Z] ' < st ud Changes text to upper case
nldisplay file content with lines numbered. Thes option is used to specify separator
nl s "| " st ud
Displays entries numbered with separator |
Result
Thus information retrieval using filters has been completed successfully.
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
stud file
[ vi j ai @l ocal host f i l t er s] $ head stud
20057801| Aar t hi | ECE | CTS | 36000
20057702| Al ber t J er r y | CSE | Wi pr o | 25000
20057903| Ar un | I T | Ramco | 12000
20057904| Di wakar | I T | TCS | 10500
20057705| Geet ha | CSE | I nf osys | 23000
20057806| I r udayar aj | ECE | Pol ar i s | 30000
20057707| J aya Pr akash | CSE | Ramco | 28000
20058008| Mahesh | EEE | Mi cr osof t | 5000
20057909| Mani mar an | I T | Mi cr osof t | 9000
20058010| Mohammed Mukt har | EEE | Or acl e | 6000
[ vi j ai @l ocal host f i l t er s] $ head -4 stud
20057801| Aar t hi | ECE | CTS | 36000
20057702| Al ber t J er r y | CSE | Wi pr o | 25000
20057903| Ar un | I T | Ramco | 12000
20057904| Di wakar | I T | TCS | 10500
[ vi j ai @l ocal host f i l t er s] $ head -1 stud | wc -c
49
[ vi j ai @l ocal host f i l t er s] $ tail stud
20058008| Mahesh | EEE | Mi cr osof t | 5000
20057909| Mani mar an | I T | Mi cr osof t | 9000
20058010| Mohammed Mukt har | EEE | Or acl e | 6000
20057711| Pr i t hi vi Raj an | CSE | Ramco | 25000
20057712| Pushpak Chander | CSE | CTS | 27500
20057713| Ramesh | CSE | Wi pr o | 24000
20057817| Smi t ha | ECE | Ramco | 30000
20057718| Sr i Gur umoor t hy | I T | Mi cr osof t | 11000
20057801| Aar t hi | ECE | CTS | 36000
20057702| Al ber t J er r y | CSE | Wi pr o | 25000
20057903| Ar un | I T | Ramco | 12000
20057904| Di wakar | I T | TCS | 10500
20057705| Geet ha | CSE | I nf osys | 23000
20057806| I r udayar aj | ECE | Pol ar i s | 30000
20057707| J aya Pr akash | CSE | Ramco | 28000
20058008| Mahesh | EEE | Mi cr osof t | 5000
20057909| Mani mar an | I T | Mi cr osof t | 9000
20058010| Mohammed Mukt har | EEE | Or acl e | 6000
20057711| Pr i t hi vi Raj an | CSE | Ramco | 25000
20057712| Pushpak Chander | CSE | CTS | 27500
20057713| Ramesh | CSE | Wi pr o | 24000
20057817| Smi t ha | ECE | Ramco | 30000
20057718| Sr i Gur umoor t hy | I T | Mi cr osof t | 11000
20057719| Tami l Sel vi | EEE | CTS | 3500
20057720| Thamot har an | I T | CTS | 9000
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
20057719| Tami l Sel vi | EEE | CTS | 3500
20057720| Thamot har an | I T | CTS | 9000
[ vi j ai @l ocal host f i l t er s] $ tail -2 stud | tee last2
20057719| Tami l Sel vi | EEE | CTS | 3500
20057720| Thamot har an | I T | CTS | 9000
[ vi j ai @l ocal host f i l t er s] $ cat l ast 2
20057719| Tami l Sel vi | EEE | CTS | 3500
20057720| Thamot har an | I T | CTS | 9000
[ vi j ai @l ocal host f i l t er s] $ cut -d \| -f 2,4-5 stud
20057801| Aar t hi | ECE
20057702| Al ber t J er r y | CSE
20057903| Ar un | I T
20057904| Di wakar | I T
20057705| Geet ha | CSE
20057806| I r udayar aj | ECE
20057707| J aya Pr akash | CSE
20058008| Mahesh | EEE
20057909| Mani mar an | I T
20058010| Mohammed Mukt har | EEE
20057711| Pr i t hi vi Raj an | CSE
20057712| Pushpak Chander | CSE
20057713| Ramesh | CSE
20057817| Smi t ha | ECE
20057718| Sr i Gur umoor t hy | I T
20057719| Tami l Sel vi | EEE
20057720| Thamot har an | I T
[ vi j ai @l ocal host f i l t er s] $ cut -d \| -f 2,4 stud > nameorg
[ vi j ai @l ocal host f i l t er s] $ cut -d \| -f 5 stud > sal
[ vi j ai @l ocal host f i l t er s] $ paste -d \| nameorg sal
Aar t hi | CTS | 36000
Al ber t J er r y | Wi pr o | 25000
Ar un | Ramco | 12000
Di wakar | TCS | 10500
Geet ha | I nf osys | 23000
I r udayar aj | Pol ar i s | 30000
J aya Pr akash | Ramco | 28000
Mahesh | Mi cr osof t | 5000
Mani mar an | Mi cr osof t | 9000
Mohammed Mukt har | Or acl e | 6000
Pr i t hi vi Raj an | Ramco | 25000
Pushpak Chander | CTS | 27500
Ramesh | Wi pr o | 24000
Smi t ha | Ramco | 30000
Sr i Gur umoor t hy | Mi cr osof t | 11000
Tami l Sel vi | CTS | 3500
Thamot har an | CTS | 9000
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
[ vi j ai @l ocal host f i l t er s] $ sort stud
20057702| Al ber t J er r y | CSE | Wi pr o | 25000
20057705| Geet ha | CSE | I nf osys | 23000
20057707| J aya Pr akash | CSE | Ramco | 28000
20057711| Pr i t hi vi Raj an | CSE | Ramco | 25000
20057712| Pushpak Chander | CSE | CTS | 27500
20057713| Ramesh | CSE | Wi pr o | 24000
20057718| Sr i Gur umoor t hy | I T | Mi cr osof t | 11000
20057719| Tami l Sel vi | EEE | CTS | 3500
20057720| Thamot har an | I T | CTS | 9000
20057801| Aar t hi | ECE | CTS | 36000
20057806| I r udayar aj | ECE | Pol ar i s | 30000
20057817| Smi t ha | ECE | Ramco | 30000
20057903| Ar un | I T | Ramco | 12000
20057904| Di wakar | I T | TCS | 10500
20057909| Mani mar an | I T | Mi cr osof t | 9000
20058008| Mahesh | EEE | Mi cr osof t | 5000
20058010| Mohammed Mukt har | EEE | Or acl e | 6000
[ vi j ai @l ocal host f i l t er s] $ sort -t \| -k 1 stud
20057801| Aar t hi | ECE | CTS | 36000
20057702| Al ber t J er r y | CSE | Wi pr o | 25000
20057903| Ar un | I T | Ramco | 12000
20057904| Di wakar | I T | TCS | 10500
20057705| Geet ha | CSE | I nf osys | 23000
20057806| I r udayar aj | ECE | Pol ar i s | 30000
20057707| J aya Pr akash | CSE | Ramco | 28000
20058008| Mahesh | EEE | Mi cr osof t | 5000
20057909| Mani mar an | I T | Mi cr osof t | 9000
20058010| Mohammed Mukt har | EEE | Or acl e | 6000
20057711| Pr i t hi vi Raj an | CSE | Ramco | 25000
20057712| Pushpak Chander | CSE | CTS | 27500
20057713| Ramesh | CSE | Wi pr o | 24000
20057817| Smi t ha | ECE | Ramco | 30000
20057718| Sr i Gur umoor t hy | I T | Mi cr osof t | 11000
20057719| Tami l Sel vi | EEE | CTS | 3500
20057720| Thamot har an | I T | CTS | 9000
[ vi j ai @l ocal host f i l t er s] $ sort -t \| -k 4,4 -k 3,3 stud
20057712| Pushpak Chander | CSE | CTS | 27500
20057801| Aar t hi | ECE | CTS | 36000
20057719| Tami l Sel vi | EEE | CTS | 3500
20057720| Thamot har an | I T | CTS | 9000
20057705| Geet ha | CSE | I nf osys | 23000
20058008| Mahesh | EEE | Mi cr osof t | 5000
20057718| Sr i Gur umoor t hy | I T | Mi cr osof t | 11000
20057909| Mani mar an | I T | Mi cr osof t | 9000
20058010| Mohammed Mukt har | EEE | Or acl e | 6000
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
20057806| I r udayar aj | ECE | Pol ar i s | 30000
20057711| Pr i t hi vi Raj an | CSE | Ramco | 25000
20057707| J aya Pr akash | CSE | Ramco | 28000
20057817| Smi t ha | ECE | Ramco | 30000
20057903| Ar un | I T | Ramco | 12000
20057904| Di wakar | I T | TCS | 10500
20057713| Ramesh | CSE | Wi pr o | 24000
20057702| Al ber t J er r y | CSE | Wi pr o | 25000
[ vi j ai @l ocal host f i l t er s] $ sort -t \| -nr -k 5 stud
20057801| Aar t hi | ECE | CTS | 36000
20057817| Smi t ha | ECE | Ramco | 30000
20057806| I r udayar aj | ECE | Pol ar i s | 30000
20057707| J aya Pr akash | CSE | Ramco | 28000
20057712| Pushpak Chander | CSE | CTS | 27500
20057711| Pr i t hi vi Raj an | CSE | Ramco | 25000
20057702| Al ber t J er r y | CSE | Wi pr o | 25000
20057713| Ramesh | CSE | Wi pr o | 24000
20057705| Geet ha | CSE | I nf osys | 23000
20057903| Ar un | I T | Ramco | 12000
20057718| Sr i Gur umoor t hy | I T | Mi cr osof t | 11000
20057904| Di wakar | I T | TCS | 10500
20057909| Mani mar an | I T | Mi cr osof t | 9000
20057720| Thamot har an | I T | CTS | 9000
20058010| Mohammed Mukt har | EEE | Or acl e | 6000
20058008| Mahesh | EEE | Mi cr osof t | 5000
20057719| Tami l Sel vi | EEE | CTS | 3500
[ vi j ai @l ocal host f i l t er s] $ tr '[a-z]' '[A-Z]' < stud
20057801| AARTHI | ECE | CTS | 36000
20057702| ALBERT J ERRY | CSE | WI PRO | 25000
20057903| ARUN | I T | RAMCO | 12000
20057904| DI WAKAR | I T | TCS | 10500
20057705| GEETHA | CSE | I NFOSYS | 23000
20057806| I RUDAYARAJ | ECE | POLARI S | 30000
20057707| J AYA PRAKASH | CSE | RAMCO | 28000
20058008| MAHESH | EEE | MI CROSOFT | 5000
20057909| MANI MARAN | I T | MI CROSOFT | 9000
20058010| MOHAMMED MUKTHAR | EEE | ORACLE | 6000
20057711| PRI THI VI RAJ AN | CSE | RAMCO | 25000
20057712| PUSHPAK CHANDER | CSE | CTS | 27500
20057713| RAMESH | CSE | WI PRO | 24000
20057817| SMI THA | ECE | RAMCO | 30000
20057718| SRI GURUMOORTHY | I T | MI CROSOFT | 11000
20057719| TAMI L SELVI | EEE | CTS | 3500
20057720| THAMOTHARAN | I T | CTS | 9000
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 1.5 Regular Expression
Aim
To search for regular expression in a file using grep command in unix.
A frequent requirement is to look for a pattern or expression in a file. Unix handles
this feature through grep and egrep. grep uses an regular expression to display lines that
match andegrep enables searching for multiple patterns. Its usage is
gr ep options searchtext filename
Command Function
gr ep t hi s demo Lists the lines that contains the stringthis
gr ep ' end of ' demo Quotes mandatoryfor text containingspace
gr ep t hi s demo* Searchthis in multiple files
gr ep c t o demo Number of occurrenceof the wordto in the file
gr ep n sequence demo Display line numbers along with matching lines
gr ep v wor d demo Displays lines that does not contain the text word
gr ep l vi m* Displays files containingtext vim
gr ep i WORD demo Search for text ignoring case differences
gr ep ' ^[ 0- 9] ' demo Lines that start with a number
gr ep ' [ 0- 9] $' demo Lines that end with a number
l s - l | gr ep " ^d" Display the subdirectory names
gr ep c " ^$" demo Display count of blank lines in the file.
gr ep "2. . . . $" st ud Display lines that ends in the range2000029999
egr ep "l ower | UPPER" demo Display lines that match either lower or upper
egr ep "( pr evi ous| cur r ent )
wor d" demo
Display lines that match either previous word or
current word
Result
Thus searching text patterns in files using grep has been completed successfully.
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
demo file
[ vi j ai @l ocal host r egexpr ] $ grep this demo
t hi s l i ne i s t he 1st l ower case l i ne i n t hi s f i l e.
Two l i nes above t hi s l i ne i s empt y.
[ vi j ai @l ocal host r egexpr ] $ grep 'end of' demo
1. e - go t o t he end of t he cur r ent wor d.
2. E - go t o t he end of t he cur r ent WORD.
[ vi j ai @l ocal host r egexpr ] $ grep -c to demo
5
[ vi j ai @l ocal host r egexpr ] $ grep -n sequence demo
15: WORD - WORD consi st s of a sequence of non- bl ank char act er s
16: Wor d - wor d consi st s of a sequence of l et t er s, di gi t s and under scor es.
[ vi j ai @l ocal host r egexpr ] $ grep -v word demo
THI S LI NE I S THE 1ST UPPER CASE LI NE I N THI S FI LE.
t hi s l i ne i s t he 1st l ower case l i ne i n t hi s f i l e.
Thi s Li ne Has Al l I t s Fi r st Char act er Of The Wor d Wi t h Upper Case.
Two l i nes above t hi s l i ne i s empt y.
vi mWor d Navi gat i on
2. E - go t o t he end of t he cur r ent WORD.
4. B - go t o t he pr evi ous WORD.
WORD - WORD consi st s of a sequence of non- bl ank char act er s
t el net 172. 16. 4. 256
THI S LI NE I S THE 1ST UPPER CASE LI NE I N THI S FI LE.
t hi s l i ne i s t he 1st l ower case l i ne i n t hi s f i l e.
Thi s Li ne Has Al l I t s Fi r st Char act er Of The Wor d Wi t h Upper Case.
Two l i nes above t hi s l i ne i s empt y.
vi mWor d Navi gat i on
You may want t o do sever al navi gat i on i n r el at i on t o wor ds, such as:
1. e - go t o t he end of t he cur r ent wor d.
2. E - go t o t he end of t he cur r ent WORD.
3. b - go t o t he pr evi ous wor d.
4. B - go t o t he pr evi ous WORD.
WORD - WORD consi st s of a sequence of non- bl ank char act er s
Wor d - wor d consi st s of a sequence of l et t er s, di gi t s and under scor es.
t el net 172. 16. 4. 256
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
[ vi j ai @l ocal host r egexpr ] $ grep -l vim *
demo r eadme
[ vi j ai @l ocal host r egexpr ] $ grep -i WORD demo
Thi s Li ne Has Al l I t s Fi r st Char act er Of The Wor d Wi t h Upper Case.
vi mWor d Navi gat i on
You may want t o do sever al navi gat i on i n r el at i on t o wor ds, such as:
1. e - go t o t he end of t he cur r ent wor d.
2. E - go t o t he end of t he cur r ent WORD.
3. b - go t o t he pr evi ous wor d.
4. B - go t o t he pr evi ous WORD.
WORD - WORD consi st s of a sequence of non- bl ank char act er s
Wor d - wor d consi st s of a sequence of l et t er s, di gi t s and under scor es.
[ vi j ai @l ocal host r egexpr ] $ grep '^[0-9]' demo
1. e - go t o t he end of t he cur r ent wor d.
2. E - go t o t he end of t he cur r ent WORD.
3. b - go t o t he pr evi ous wor d.
4. B - go t o t he pr evi ous WORD.
[ vi j ai @l ocal host r egexpr ] $ grep '[0-9]$' demo
t el net 172. 16. 4. 256
[ vi j ai @l ocal host vi j ai ] $ ls -l | grep "^d"
dr wxr wxr - x 2 vi j ai vi j ai 4096 Apr 9 14: 30 r egexpr
dr wxr wxr - x 7 vi j ai vi j ai 4096 Apr 4 14: 57 shel l scr i pt s
[ vi j ai @l ocal host r egexpr ] $ grep -c "^$" demo
5
[ vi j ai @l ocal host r egexpr ] $ egrep "lower|UPPER" demo
THI S LI NE I S THE 1ST UPPER CASE LI NE I N THI S FI LE.
t hi s l i ne i s t he 1st l ower case l i ne i n t hi s f i l e.
[ vi j ai @l ocal host r egexpr ] $ egrep "(previous|current) word" demo
1. e - go t o t he end of t he cur r ent wor d.
3. b - go t o t he pr evi ous wor d.
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 2.1 SIMPLE PROGRAMS
Aim
To write simple shell programs using shell programming fundamentals.
The activities of a shell are not restricted to command interpretation alone. The shell also has
rudimentary programming features. When a group of commands has to be executed regularly,
they are stored in a file (with extension .sh). All such files are called shell scripts or shell
programs. Shell programs run in interpretive mode.
The original UNIX came with the Bourne shell (sh) and it is universal even today. Then
came a plethora of shells offering new features. Two of them, C shell (csh) and Korn shell
(ksh) has been well accepted by the UNIX fraternity. Linux offers Bash shell (bash) as a
superior alternative to Bourne shell.
Preliminaries
1. Comments in shell script start with #. It can be placed anywhere in a line; the shell
ignores contents to its right. Comments are recommended but not mandatory
2. Shell variables are loosely typed i.e. not declared. Their type depends on the value
assigned. Variables when used in an expression or output must be prefixed by$.
3. Theread statement is shell's internal tool for making scripts interactive.
4. Output is displayed usingecho statement. Any text should be within quotes. Escape
sequence should be used withe option.
5. Commands are always enclosed with` ` (back quotes).
6. Expressions are computed using the expr command. Arithmetic operators are+ -
* / %. Meta characters* ( ) should be escaped with a\.
7. Multiple statements can be written in a single line separated by;
8. The shell scripts are executed using thesh command (sh filename).
Result
Thus using programming basics, simple shell scripts were executed
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
2.1.ASwapping values of two variables
Algorithm
Step 1 : Start
Step 2 : Read the values of a andb
Step 3 : Interchange the values of a andb using another variablet as follows:
t =a
a =b
b =t
Step 4 : Print a andb
Step 5 : Stop
Program (swap.sh)
# Swappi ng val ues
echo - n "Ent er val ue f or A : "
r ead a
echo - n "Ent er val ue f or B : "
r ead b
t =$a
a=$b
b=$t
echo "Val ues af t er Swappi ng"
echo "A Val ue i s $a"
echo "B Val ue i s $b"
Output
[ vi j ai @l ocal host si mpl e] $ sh swap.sh
Ent er val ue f or A : 12
Ent er val ue f or B : 23
Val ues af t er Swappi ng
A Val ue i s 23
B Val ue i s 12
2.1.BFarenheit to Centigrade Conversion
Algorithm
Step 1 : Start
Step 2: Readfahrenheit value
Step 3 : Convert fahrenheit tocentigrade using the formulae: (fahrenheit 32) 5/9
Step4: Print centigrade
Step 5 : Stop
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Program (degconv.sh)
# Degr ee conver si on
echo - n "Ent er Fahr enhei t : "
r ead f
c=`expr \ ( $f - 32 \ ) \ * 5 / 9`
echo "Cent i gr ade i s : $c"
Output
[ vi j ai @l ocal host si mpl e] $ sh degconv.sh
Ent er Fahr enhei t : 213
Cent i gr ade i s : 100
2.1.C Area & Circumference of Circle
Algorithm
Step 1: Start
Step 2 : Define constant pi =3.14
Step 3 : Read the value of radius
Step 4 : Calculatearea using formulae: pi radius
2
Step 5 : Calculatecircumference using formulae: 2 pi radius
Step 6 : Print area andcircumference
Step 7 : Stop
Program (circle.sh)
# Ci r cl e met r i cs usi ng r eadonl y var i abl e
pi =`expr "scal e=2; 22 / 7" | bc`
r eadonl y pi # pi val ue cannot be al t er ed
echo - n "Ent er val ue f or r adi us : "
r ead r adi us
ar ea=`expr "scal e=2; $pi * $r adi us * $r adi us" | bc`
ci r cum=`expr "scal e=2; 2 * $pi * $r adi us" | bc`
echo "Ar ea : $ar ea"
echo "Ci r cumf er ence : $ci r cum"
Output
[ vi j ai @l ocal host si mpl e] $ sh circle.sh
Ent er val ue f or r adi us : 12
Ar ea : 452. 16
Ci r cumf er ence : 75. 36
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
2.1.D Simple Interest Calculation
Algorithm
Step 1 : Start
Step 2: Read the valuesprincipal, rate andyears
Step 3 : Computesimpleinterest using the formulae: (principal rate years) / 100
Step4: Print simpleinterest
Step 5 : Stop
Program (simpint.sh)
# I nt er est comput at i on usi ng bc
echo - n "Ent er Pr i nci pal amount : "
r ead p
echo - n "Ent er number of year s : "
r ead n
echo - n "Ent er r at e of i nt er est : "
r ead r
si =`expr "scal e=2; $p * $n *$r / 100" | bc`
echo "Si mpl e I nt er est : $si "
Output
[ vi j ai @l ocal host si mpl e] $ sh simpint.sh
Ent er Pr i nci pal amount : 1285
Ent er number of year s : 3
Ent er r at e of i nt er est : 5
Si mpl e I nt er est : 192. 75
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 2.2 CONDITIONAL STATEMENT
Aim
To write shell programs using decision-making constructs.
Shell supports decision-makingusingif statement. Theif statement like its counterpart in
programming languages has the following formats. The first construct executes the
statements when the condition is true. The second construct adds an optional else to the
first one that has different set of statements to be executed depending on whether the
condition is true or false. The last one is an elif ladder, in which conditions are tested in
sequence, but only one set of statements is executed.
i f [ condition ]
t hen
statements
f i
i f [ condition ]
t hen
statements
el se
statements
f i
i f [ condition ]
t hen
statements
el i f [ condition ]
t hen
statements
.. .
el se
statements
f i
The set of relational and logical operators used in conditional expression is given below. The
numeric comparison in the shell is confined to integer values only.
Operator Description
- eq Equal to
- ne Not equal to
- gt Greater than
- ge Greater than or equal to
- l t Less than
- l e Less than or equal to
- a Logical AND
- o Logical OR
! Logical NOT
Result
Thus using if statement scripts with conditional expressions were executed
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
2.2.A Odd or even
Algorithm
Step 1 : Start
Step 2 : Readnumber
Step 3 : If number divisible by 2 then
Print "Number is Even"
Step 3.1 : else
Print "Number is Odd"
Step 4 : Stop
Program (oddeven.sh)
# Odd or even usi ng i f - el se
echo - n "Ent er a non- zer o number : "
r ead num
r em=`expr $num%2`
i f [ $r em- eq 0 ]
t hen
echo "$numi s Even"
el se
echo "$numi s Odd"
f i
Output
[ vi j ai @l ocal host deci si on] $ sh oddeven.sh
Ent er a non- zer o number : 12
12 i s Even
2.2.BBiggest of 3 numbers
Algorithm
Step 1 : Start
Step 2 : Read values of a, b andc
Step 3 : If a > b anda > c then
Print "A is the biggest"
Step 3.1 : else if b >c then
Print "B is the biggest "
Step 3.2 : else
Print "C is the biggest"
Step 4 : Stop
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Program (big3.sh)
# Bi ggest usi ng l ogi cal expr essi on
echo - n "Gi ve val ue f or A B and C: "
r ead a b c
i f [ $a - gt $b - a $a - gt $c ]
t hen
echo "A i s t he Bi ggest number "
el i f [ $b - gt $c ]
t hen
echo "B i s t he Bi ggest number "
el se
echo "C i s t he Bi ggest number "
f i
Output
[ vi j ai @l ocal host deci si on] $ sh big3.sh
Gi ve val ue f or A B and C: 4 3 4
C i s t he Bi ggest number
2.2.CLeap year
Algorithm
Step 1 : Start
Step 2 : Read the value of year
Step 3 : If year divisible by 400 then
Print "Leap year"
Step 3.1 : else if year divisible by 4 andnot divisible by100 then
Print "Leap year"
Step3.2 : else
Print "Not a leap year"
Step 4 : Stop
Program (leap.sh)
# Leap year
echo - n "Ent er a year : "
r ead year
r em1=`expr $year %4`
r em2=`expr $year %100`
r em3=`expr $year %400`
i f [ $r em3 - eq 0 ]
t hen
echo "$year i s a Leap Year "
el i f [ $r em2 - ne 0 - a $r em1 - eq 0 ]
t hen
echo "$year i s a Leap Year "
el se
echo "$year i s Not a l eap year "
f i
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Output
[ vi j ai @l ocal host deci si on] $ sh leap.sh
Ent er a year : 1900
1900 i s Not a l eap year
2.2.DGrade Determination
Algorithm
Step 1 : Start
Step 2 : Readmark
Step 3 : If mark >90 then
Print "S grade"
Step 3.1 : else if mark >80 then
Print "A grade"
Step 3.2 : else if mark >70 then
Print "B grade"
Step 3.3 : else if mark >60 then
Print "C grade"
Step 3.4 : else if mark >55 then
Print "D grade"
Step 3.5 : else if mark 50 then
Print "E grade"
Step 3.6 : else
Print "U grade"
Step 4 : Stop
Program (grade.sh)
echo - n "Ent er t he mar k : "
r ead mar k
i f [ $mar k - gt 90 ]
t hen
echo "S Gr ade"
el i f [ $mar k - gt 80 ]
t hen
echo "A Gr ade"
el i f [ $mar k - gt 70 ]
t hen
echo "B Gr ade"
el i f [ $mar k - gt 60 ]
t hen
echo "C Gr ade"
el i f [ $mar k - gt 55 ]
t hen
echo "D Gr ade"
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
el i f [ $mar k - ge 50 ]
t hen
echo "E Gr ade"
el se
echo "U Gr ade"
f i
Output
[ vi j ai @l ocal host deci si on] $ sh grade.sh
Ent er t he mar k : 65
C Gr ade
2.2.EString comparison
Algorithm
Step 1 : Start
Step 2 : Read stringsstr1 andstr2
Step 3 : If str1 =str2 then
Print "Strings are the same"
Step 3.1 : else
Print "Strings are distinct"
Step 4 : Stop
Program (strcomp.sh)
echo - n "Ent er t he f i r st st r i ng : "
r ead s1
echo - n "Ent er t he second st r i ng : "
r ead s2
i f [ $s1 == $s2 ]
t hen
echo "St r i ngs ar e t he same"
el se
echo "St r i ngs ar e di st i nct "
f i
Output
[ vi j ai @l ocal host deci si on] $ sh strcomp.sh
Ent er t he f i r st st r i ng : ece- a
Ent er t he second st r i ng : ECE- A
St r i ngs ar e di st i nct
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
2.2.FEmployee Pay Calculation
Algorithm
Step 1 : Start
Step 2 : Readbasic
Step 3 : If basic >30000 then
hra is 5% of basic
da is 5% of basic
tax is 10% of basic
Step 3.1 : else if basic >20000 then
hra is 4% of basic
da is 3% of basic
tax is 8% of basic
Step 3.2 : else
hra is 3% of basic
da is 2% of basic
tax is 5% of basic
Step 4 : Stop
Program (emppay.sh)
echo - n "Ent er empl oyee basi c pay : "
r ead basi c
i f [ $basi c - gt 30000 ]
t hen
hr a=`expr 5 \ * $basi c / 100`
da=`expr 5 \ * $basi c / 100`
t ax=`expr 10 \ * $basi c / 100`
el i f [ $basi c - gt 20000 ]
t hen
hr a=`expr 4 \ * $basi c / 100`
da=`expr 3 \ * $basi c / 100`
t ax=`expr 8 \ * $basi c / 100`
el se
hr a=`expr 3 \ * $basi c / 100`
da=`expr 2 \ * $basi c / 100`
t ax=`expr 5 \ * $basi c / 100`
f i
gr oss=`expr $basi c + $da + $hr a`
net pay=`expr $gr oss - $t ax`
echo "Gr oss Pay : $gr oss"
echo "Net Pay : $net pay"
Output
[ vi j ai @l ocal host deci si on] $ sh emppay.sh
Ent er empl oyee basi c pay : 12000
Gr oss Pay : 12600
Net Pay : 12000
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 2.3 MULTI-WAY BRANCHING
Aim
To write shell programs using case construct to match patterns.
Thecase statement is used to compare a variables value against a set of constants (integer,
character, string, range). If it matches a constant, then the set of statements followed after ) is
executed till a ; ; is encountered. The optional default block is indicated by *. Multiple
constants can be specified in a single pattern separated by|.
case variable i n
constant1)
statements ; ;
constant2)
statements ; ;
. . .
constantN)
statements ; ;
*)
statements
esac
Result
Thus using case statement, shell scripts were executed
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
2.3.AVowel or Consonant
Algorithm
Step 1 : Start
Step 2 : Readchar
Step 3 : If char is either 'a', 'e', 'i', 'o' or 'u' then
Print "It's a vowel"
Step 3.1 : else
Print "It's a consonant"
Step 4 : Stop
Program (vowel.sh)
# Vowel wi t h mul t i pl e val ues i n a pat t er n
echo - n "Key i n a l ower case char act er : "
r ead choi ce
case $choi ce i n
a| e| i | o| u) echo "I t ' s a Vowel "; ;
*) echo "I t ' s a Consonant "
esac
Output
[ vi j ai @l ocal host mul t way] $ sh vowel.c
Key i n a l ower case char act er : e
I t ' s a Vowel
2.3.BSimple Calculator
Algorithm
Step 1 : Start
Step 2 : Read operandsa andb
Step 3 : Display operation menu
Step 4 : Readoption
Step 5 : If option =1 then
Calculatec =a +b
Step 5.1 : else if option =2 then
Calculatec =a b
Step 5.2 : else if option =3 then
Calculatec =a * b
Step 5.3 : else if option =4 then
Calculatec =a / b
Step 5.4 : else if option =5 then
Calculatec =a %b
Step 5.5 : else
Print "Invalid option"
Step 6 : Print c
Step 7 : Stop
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Program (calc.sh)
# Ar i t hmet i c oper at i ons- - mul t i pl e st at ement s i n a bl ock
echo - n "Ent er t he t wo number s : "
r ead a b
echo " 1. Addi t i on"
echo " 2. Subt r act i on"
echo " 3. Mul t i pl i cat i on"
echo " 4. Di vi si on"
echo " 5. Modul o Di vi si on"
echo - n "Ent er t he opt i on : "
r ead opt i on
case $opt i on i n
1) c=`expr $a + $b`
echo "$a + $b = $c"; ;
2) c=`expr $a - $b`
echo "$a - $b = $c"; ;
3) c=`expr $a \ * $b`
echo "$a * $b = $c"; ;
4) c=`expr $a / $b`
echo "$a / $b = $c"; ;
5) c=`expr $a %$b`
echo "$a %$b = $c"; ;
*) echo "I nval i d Opt i on"
esac
Output
[ vi j ai @l ocal host mul t way] $ sh calc.sh
Ent er t he t wo number s : 2 4
1. Addi t i on
2. Subt r act i on
3. Mul t i pl i cat i on
4. Di vi si on
5. Modul o Di vi si on
Ent er t he opt i on : 1
2 + 4 = 6
2.3.CRental Options
Algorithm
Step 1 : Start
Step 2 : Readvehicle
Step 3 : If vehicle ="car" then
Print "Rental is Rs. 20/km"
Step 3.1 : else if vehicle ="van" then
Print "Rental is Rs. 10/km"
Step 3.2 : else if vehicle ="jeep" then
Print "Rental is Rs. 5/km"
Step 3.3 : else if vehicle ="bicycle" then
Print "Rental is Rs. 0.2/km"
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Step 3.4 : else
Print "Vehicle not available"
Step 4 : Stop
Program (rental.sh)
# St r i ng mat chi ng
echo "Two/ Four wheel er r ent al "
echo - n "Ent er t he r equi r ed vehi cl e : "
r ead vehi cl e
case $vehi cl e i n
"car ") echo " For $vehi cl e Rs. 20 per km"; ;
"van") echo " For $vehi cl e Rs. 10 per km"; ;
"j eep") echo " For $vehi cl e Rs. 5 per km" ; ;
"bi cycl e") echo " For $vehi cl e 20 pai sa per km"; ;
*) echo " Sor r y, I cannot get a $vehi cl e f or you"; ;
esac
Output
[ vi j ai @l ocal host mul t way] $ sh rental.sh
Two/ Four wheel er r ent al
Ent er t he r equi r ed vehi cl e : bi cycl e
For bi cycl e 20 pai sa per km
2.3.DVote Eligibility (vote.sh)
Algorithm
Step 1 : Start
Step 2 : Readage
Step 3 : If age 17
Print "Not eligible to vote"
Step 3.1 : else
Print "Eligible to vote"
Step 4 : Stop
Program
# Vot e- - r ange mat chi ng
echo - n "Ent er your age : "
r ead age
case $age i n
[ 0- 9] | 1[ 0- 7] ) echo "You ar e not el i gi bl e t o vot e"; ;
*) echo "El i gi bl e t o vot e"
esac
Output
[ vi j ai @l ocal host mul t way] $ sh vote.sh
Ent er your age : 12
You ar e not el i gi bl e t o vot e
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 2.4 LOOPS
Aim
To write shell programs using different types of loops.
Shell supports a set of loops such asfor, while anduntil to execute a set of statements
repeatedly. The body of the loop is contained betweendo anddone statement.
Thefor loop doesn't test a condition, but uses a list instead.
f or variable i n list
do
statements
done
Thewhile loop executes thestatements as long as the condition remains true.
whi l e [ condition ]
do
statements
done
Theuntil loop complements the while construct in the sense that thestatements are executed
as long as the condition remains false.
unt i l [ condition ]
do
statements
done
Result
Thus using loops, iterative scripts were executed
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
2.4.AMultiplication Table
Algorithm
Step 1 : Start
Step 2 : Read the value of n
Step 3 : Initialize 1 toi
Step 4 : Print n, i, ni
Step 5 : Increment i by 1
Step 6 : Repeat steps 4 and 5until i 10
Step 7 : Stop
Program (multable.sh)
# Mul t i pl i cat i on t abl e usi ng f or l oop
cl ear
echo - n "Whi ch mul t i pl i cat i on t abl e? : "
r ead n
f or x i n 1 2 3 4 5 6 7 8 9 10
do
p=`expr $x \ * $n`
echo - n "$n X $x = $p"
sl eep 1
done
Output
[ vi j ai @l ocal host l oops] $ sh multable.sh
Whi ch mul t i pl i cat i on t abl e? : 6
6 X 1 = 6
6 X 2 = 12
6 X 3 = 18
6 X 4 = 24
6 X 5 = 30
6 X 6 = 36
6 X 7 = 42
6 X 8 = 48
6 X 9 = 54
6 X 10= 60
2.4.BArmstrong Number
Algorithm
Step 1 : Start
Step 2 : Readnumber
Step 3 : Initialize 0 tosum andnumber tonum
Step 4 : Extract lastdigit by computingnumber modulo 10
Step 5 : Cube thelastdigit and add it tosum
Step 6 : Dividenumber by 10
Step 7: Repeat steps 46until number >0
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Step 8 : If sum =number then
Print Armstrong number
Step 8.1 : else
Print Not an Armstrong number
Step 9 : Stop
Program (armstrong.sh)
# Ar mst r ong number usi ng whi l e l oop
echo - n "Ent er a number : "
r ead n
a=$n
s=0
whi l e [ $n - gt 0 ]
do
r =`expr $n %10`
s=`expr $s + \ ( $r \ * $r \ * $r \ ) `
n=`expr $n / 10`
done
i f [ $a - eq $s ]
t hen
echo "Ar mst r ong Number "
el se
echo - n "Not an Ar mst r ong number "
f i
Output
[ vi j ai @l ocal host l oops] $ sh armstrong.sh
Ent er a number : 370
Ar mst r ong Number
2.4.CNumber Reverse
Algorithm
Step 1 : Start
Step 2 : Readnumber
Step 3 : Initialize 0 toreverse
Step 4 : Extract lastdigit by computingnumber modulo 10
Step 5 : Computereverse =reverse
10
+lastdigit
Step 6 : Dividenumber by 10
Step 7: Repeat steps 46until number >0
Step 8 : Print reverse
Step 9 : Stop
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Program (reverse.sh)
# To r ever se a number usi ng whi l e l oop
echo - n "Ent er a number : "
r ead n
r d=0
whi l e [ $n - gt 0 ]
do
r em=`expr $n %10`
r d=`expr $r d \ * 10 + $r em`
n=`expr $n / 10`
done
echo "Rever sed number i s $r d"
Output
[ vi j ai @l ocal host l oops] $ sh reverse.sh
Ent er a number : 234
Rever sed number i s 432
2.4.DFibonacci Series
Algorithm
Step 1 : Start
Step 2 : Read number of terms asn
Step 3 : Initialize 0 tof1, 1 tof2 and 2 toi
Step 4 : Print initial fibonacci terms f1, f2
Step 5 : Generate next term using the formulaf3 =f1 +f2
Step 6 : Print f3
Step 7 : Increment i by 1
Step 8 : Assignf2 tof1
Step 9 : Assignf3 tof2
Step 10 : Repeat steps 59until i n
Step 11 : Stop
Program (fibo.sh)
# Fi bonacci ser i es usi ng whi l e l oop
echo - n "Ent er number of t er ms : "
r ead n
echo "Fi bonacci Ser i es"
f 1=0
f 2=1
echo - n "$f 1 "
echo - n " $f 2 "
i =2
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
whi l e [ $i - l t $n ]
do
f 3=`expr $f 1 + $f 2`
echo - n " $f 3 "
f 1=$f 2
f 2=$f 3
i =`expr $i + 1`
done
echo
Output
[ vi j ai @l ocal host l oops] $ sh fibo.sh
Ent er number of t er ms : 8
Fi bonacci Ser i es
0 1 1 2 3 5 8 13
2.4.EPrime Number
Algorithm
Step 1 : Start
Step 2 : Read the value of n
Step 3 : Initializei to 2
Step 4 : If n is divisible byi then
Print Not Prime and Stop
Step 5 : Increment i by 1
Step 6 : Repeat steps 4 and 5until i n/2
Step 7 : Print "Prime"
Step 8 : Stop
Program (prime.sh)
# Pr i me number usi ng exi t
echo - n "Ent er t he number : "
r ead n
i =2
m=`expr $n / 2`
unt i l [ $i - gt $m]
do
q=`expr $n %$i `
i f [ $q - eq 0 ]
t hen
echo " Not a Pr i me number "
exi t
f i
i =`expr $i + 1`
done
echo "Pr i me number "
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Output
[ vi j ai @l ocal host l oops] $ sh prime.sh
Ent er t he number : 17
Pr i me number
2.4.FFactorial Value
Algorithm
Step 1 : Start
Step 2 : Readnumber
Step 3 : Initialize 1 tofact andnumber toi
Step 4 : fact =fact * i
Step 5 : Decrement i by 1
Step 6: Repeat steps 46until i >0
Step 7 : Print fact
Step 8 : Stop
Program (fact.sh)
# Fact or i al val ue usi ng unt i l
echo - n "Ent er a posi t i ve number : "
r ead n
f =1
unt i l [ $n - l t 1 ]
do
f =`expr $f \ * $n`
n=`expr $n - 1`
done
echo "Fact or i al val ue : $f "
Output
[ vi j ai @l ocal host l oops] $ sh fact.sh
Ent er a posi t i ve number : 10
Fact or i al val ue : 3628800
2.4.GSum of 1..N natural numbers
Algorithm
Step 1 : Start
Step 2 : Readn
Step 3 : Initialize 0 tosum and 1 toi
Step 4 : Addi tosum
Step 5 : Increment i by 1
Step 6: Repeat steps 46until i n
Step 7 : Print sum
Step 8 : Stop
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Program (sum1ton.sh)
# Sumof 1+2+3+ . . . +N number s
echo - n "Ent er N val ue : "
r ead n
sum=0
i =1
unt i l [ $i - gt $n ]
do
sum=`expr $sum+ $i `
i =`expr $i + 1`
done
echo "The sumof n number s i s $sum"
Output
[ vi j ai @l ocal host l oops] $ sh sum1ton.sh
Ent er N val ue : 26
The sumof n number s i s 351
2.4.HData Statistics
Algorithm
Step 1 : Start
Step 2 : Initialize0topc, sum, i
Step 3 : Read anumber
Step 4 : If number =9999 then goto step 10
Step 5 : Increment i by 1
Step 6 : If number 0 then goto step 3
Step 7 : Increment pc by 1
Step 8 : Addnumber tosum
Step 9 : Goto step 3
Step 10 : Computeavg =sum / pc
Step 11 : Print i, pc, avg,
Step 12 : Stop
Program (datastat.sh)
# Aggr egat e of posi t i ve nos usi ng br eak and cont i nue
cl ear
pc=0
s=0
i =0
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
unt i l f al se
do
echo - n "Ent er a number ( 9999 t o qui t ) : "
r ead n
i f [ $n - eq 9999 ]
t hen
br eak
f i
i =`expr $i + 1`
i f [ $n - l e 0 ]
t hen
cont i nue
f i
pc=`expr $pc + 1`
s=`expr $s + $n`
done
avg=`expr "scal e=2; $s / $pc" | bc`
echo "Tot al No. of ent r i es : $i "
echo "No. of posi t i ve dat as : $pc"
echo "Posi t i ve aggr egat e : $avg"
Output
[ vi j ai @l ocal host l oops] $ sh datastat.sh
Ent er a number ( 9999 t o qui t ) : 32
Ent er a number ( 9999 t o qui t ) : 78
Ent er a number ( 9999 t o qui t ) : 0
Ent er a number ( 9999 t o qui t ) : 11
Ent er a number ( 9999 t o qui t ) : 47
Ent er a number ( 9999 t o qui t ) : - 9
Ent er a number ( 9999 t o qui t ) : 12
Ent er a number ( 9999 t o qui t ) : 7
Ent er a number ( 9999 t o qui t ) : 9999
Tot al No. of ent r i es : 8
No. of posi t i ve dat as : 6
Posi t i ve aggr egat e : 31. 16
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 2.5 SHELL SCRIPTS
Aim
To write shell scripts using shell commands.
The shell's programming features coupled with the UNIX commands make it an extremely
useful programming language. It is programming practice to tell the system that the file
contents are set of commands to be interpreted by the specified shell in the first line as
#! / bi n/ bash
File Test operations
The following are some of the options for test expressions that work with files.
Condition Return value
- e filename true if file exists
- f filename true if file exists and is ordinary
- d filename true if file exists and is directory
- r filename true if file exists and is readable
- wfilename true if file exists and is writeable
- x filename true if file exists and is executable
- s filename true if file exists and is non-empty
file1 - nt file2 true if file1 is newer than file2
Special Variables
Shell posses certain special variables prefixed by a$ reserved for specific functions. These
are also known as positional parameters. Some of them are
Variable Description
$0 Name of the script
$n
Command-line arguments ($1 for first, $2 for second argument, and so on)
$# Number of arguments supplied to the script
$? Exit status of the recent command
Result
Thus programming constructs using shell commands were executed
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
2.5.ATime based greeting
Program (wish.sh)
#! / bi n/ bash
x=`dat e +%H`
mr d=`dat e +%P`
i f [ $mr d==' am' ]
t hen
i f [ $x - l e 11 ]
t hen
echo "Good Mor ni ng"
f i
el se
i f [ $x - l e 2 ]
t hen
echo "Good Af t er noon"
el i f [ $x - l e 6 ]
t hen
echo "Good Eveni ng"
el se
echo "Good Ni ght "
f i
f i
Output
[ vi j ai @l ocal host command] $ sh wish.sh
Good Mor ni ng
2.5.BNumber of days in a month
Program (monthdays.sh)
# Number of days i n a mont h
mt h=`dat e +%m`
mn=`dat e +%B`
case $mt h i n
02) echo "Febr uar y usual l y has 28 days"
echo "I f l eap year , t hen i t has 29 days" ; ;
04| 06| 09| 11) echo "The cur r ent mont h $mn has 30 days" ; ;
*) echo "The cur r ent mont h $mn has 31 days"
esac
Output
[ vi j ai @l ocal host command] $ sh monthdays.sh
The cur r ent mont h Apr i l has 30 days
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
2.5.CCommands menu
Program (cmdmenu.sh)
# Menu pr ogr am
ch=' y'
whi l e [ $ch == ' y' ]
do
echo - e "\ t MENU
1. Li st of f i l es
2. Wor ki ng Di r ect or y
3. Dat e and Ti me
4. User s of t he syst em
5. Cal endar
Ent er t he opt i on : \ c"
r ead choi ce
case " $choi ce" i n
1) l s - l ; ;
2) pwd ; ;
3) dat e ; ;
4) who ; ;
5) cal
esac
echo - n "Do you wi sh t o cont i nue ( y/ n) : "
r ead ch
done
Output
[ vi j ai @l ocal host command] $ sh cmdmenu.sh
MENU
1. Li st of f i l es
2. Wor ki ng Di r ect or y
3. Dat e and Ti me
4. User s of t he syst em
5. Cal endar
Ent er t he opt i on : 4
vi j ai pt s/ 20 Apr 4 13: 41 ( l i nux- 21. smkf omr a. com)
cse1 pt s/ 13 Apr 4 13: 43 ( scl - 58. smkf omr a. com)
Do you wi sh t o cont i nue ( y/ n) : n
2.5.DDirectory Listing
Program (cmdmenu.sh)
f or x i n .
do
l s - R $x
done
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Output
[ vi j ai @l ocal host command] $ sh list.sh
. :
l i st . sh shel l scr i pt s
. / shel l scr i pt s:
command deci si on l oops pat mat ch si mpl e
. / shel l scr i pt s/ command:
cmdmenu. sh debug. sh dupr emove. sh f i l et ype. sh keyst r oke. sh
. / shel l scr i pt s/ deci si on:
bi g3. sh emppay. sh gr ade. sh l eap. sh oddeven. sh st r comp. sh
. / shel l scr i pt s/ l oops:
ar mst r ong. sh dat ast at . sh f act . sh f i bo. sh mul t abl e. sh
. / shel l scr i pt s/ pat mat ch:
cal c. sh r ent al . sh vot e. sh vowel . sh
. / shel l scr i pt s/ si mpl e:
ci r cl e. sh degconv. sh si mpi nt . sh swap. sh
2.5.EDetecting file type
Program (filetype.sh)
# Fi l e t ype
echo - n "Ent er f i l ename : "
r ead f name
i f [ - e $f name ]
t hen
i f [ - f $f name ]
t hen
echo "Regul ar f i l e"
el i f [ - d $f name ]
t hen
echo "Di r ect or y"
el se
echo "Speci al f i l e"
f i
el se
echo "Fi l e does not exi st "
f i
Output
[ vi j ai @l ocal host command] $ sh f i l et ype. sh
Ent er f i l ename : samp. c
Regul ar f i l e
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
2.5.FDetecting user when logged on
Program (logdetect.sh)
#! / bi n/ bash
#Det ect t he user at l ogon
whi l e t r ue
do
i f who| gr ep $1>/ dev/ nul l
t hen
echo $1 i s l ogged i n
exi t
f i
done
Output
[ vi j ai @l ocal host command] $ sh logdetect.sh cse1
cse1 i s l ogged i n
2.5.GDuplicate file removal
Program (dupremove.sh)
# Dupl i cat e f i l e r emoval
i f cmp $1 $2
t hen
echo "Fi l es $1, $2 ar e i dent i cal "
r m$2
echo "$2 f i l e del et ed"
el se
echo "Fi l es $1, $2 ar e di st i nct "
f i
Output
[ vi j ai @l ocal host command] $ sh dupremove.sh samp.c s.c
Fi l es samp. c, s. c ar e i dent i cal
s. c f i l e del et ed
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
2.5.HCompilation and execution of a C program
Program (debug.sh)
# Compi l e and execut e
whi l e t r ue
do
gcc - o $1. out $1. c
case " $?" i n
0) echo " Execut i ng . . . "
. / $1. out
exi t ; ;
*)
sl eep 5
vi $1. c
esac
done
Output
[ vi j ai @l ocal host command] $ sh debug. sh samp
samp. c: 4: 10: war ni ng: mul t i - l i ne st r i ng l i t er al s ar e
depr ecat ed
samp. c: 4: 10: mi ssi ng t er mi nat i ng " char act er
samp. c: 4: 10: possi bl e st ar t of unt er mi nat ed st r i ng l i t er al
samp. c: I n f unct i on `mai n' :
samp. c: 4: par se er r or at end of i nput
Execut i ng . . .
Hel l o
2.5.IKeystroke detection
Program (keystroke.sh)
# Det ect key st r oke
echo "Hi t a key and t hen hi t r et ur n. "
r ead Keypr ess
case "$Keypr ess" i n
[ [ : l ower : ] ] ) echo "Lower case l et t er "; ;
[ [ : upper : ] ] ) echo "Upper case l et t er "; ;
[ 0- 9] ) echo "Di gi t " ; ;
* ) echo "Punct uat i on, whi t espace, or ot her "; ;
esac
Output
[ vi j ai @l ocal host command] $ sh keyst r oke. sh
8
Di gi t
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 3.1 Introduction to Pointers
Aim
To learn the concept of pointers in C programs.
Data for a variable is stored at some memory location. Address and Data are two sides an
variable. For instance x =10 is represented as
Variable Data Address
x 3221216948
The address of a variable can be obtained using& operator known asreference operator. The
variable's value can be obtained using the dereference operator *.
Pointer Variable
A Pointer variable or a pointer is a special variable that holds the address of another variable.
Pointer variable are distinguished from other variables by having an asterik (*) prefixed in the
declaration statement.
i nt x, *i pt r ;
A pointer variable is a derived data type based on either standard, derived or user-defined
data type. A pointer variable can be made to point any variable of its base type by assigning
the variable's address to the pointer. For instance, an integer pointer can point to an integer
variable only. A pointer variable is allocated 2 bytes irrespective of the data type it points.
pt r = &x; / * Assi gni ng addr ess X t o poi nt er */
Value of the variable pointed to can be accessed by applying the dereference operator
pr i nt f ( " Val ue of t he var i abl e poi nt ed t o %d", *pt r ) ;
A pointer of type void is referred to asgeneric pointer i.e. it can point to any data type. Since
pointer variables hold address, integers could be added or subtracted to yield another address.
A pointer that holds the address of another pointer variable is known aspointer-to-pointer.
Result
Thus C programs using pointers were executed.
10
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
3.1.AReference and Dereference operator
Algorithm
Step 1 : Start
Step 2 : Initializex to 10
Step 3 : Print the value of x
Step 4 : Print the address of x using address operator
Step 5 : Print the value of x by dereferencing the address operator
Step 6 : Stop
Program (refderef.c)
/ * Dat a and addr ess */
#i ncl ude <st di o. h>
mai n( )
{
i nt x;
x=10;
pr i nt f ( "Val ue of x i s %d", x) ;
pr i nt f ( "\ nAddr ess of x i s %u" , &x) ;
pr i nt f ( "\ nVal ue of x i s %d\ n" , *( &x) ) ;
}
Output
[ vi j ai @l ocal host poi nt er ] $ gcc refderef.c
[ vi j ai @l ocal host poi nt er ] $ ./a.out
Val ue of x i s 10
Addr ess of x i s 3221216948
Val ue of x i s 10
3.1.BPointer variables
Algorithm
Step 1 : Initialize two integer variablesx andy with some values.
Step 2 : Create a pointer iptr of integer type
Step 3 : Assign the address of x toiptr
Step 4 : Print the value and address stored iniptr
Step 5 : Assign the address of y toiptr
Step 6 : Print the value and address stored iniptr
Step 7 : Print the storage requirement of iptr, address of iptr andmain function
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Program (ptrvar.c)
/ * Poi nt er var i abl es */
# i ncl ude<st di o. h>
mai n( )
{
i nt x, y, *i pt r ;
x = 125;
i pt r = &x ; / * i pt r poi nt s t o x */
y = 23;
f l oat *f pt r ;
pr i nt f ( "X val ue i s %d and st or ed at %u\ n", x, &x) ;
pr i nt f ( "Y val ue i s %d and st or ed at %u\ n", y, &y) ;
pr i nt f ( "\ nI nt poi nt er hol ds t he addr ess %u\ n", i pt r ) ;
pr i nt f ( "Aceesi ng val ue t hr u poi nt er : %d\ n", *i pt r ) ;
i pt r = &y; / * i pt r poi nt s t o y */
pr i nt f ( "\ nI nt poi nt er now hol ds t he addr ess %u\ n" , i pt r ) ;
pr i nt f ( "Accessi ng val ue t hr u poi nt er : %d\ n" , *i pt r ) ;
pr i nt f ( "\ nSi ze of i nt poi nt er : %d byt es", si zeof ( i pt r ) ) ;
pr i nt f ( "\ nSi ze of f l oat poi nt er : %d byt es", si zeof ( f pt r ) ) ;
pr i nt f ( "\ n\ nAddr ess of mai n f unct i on i s %u\ n", mai n) ;
}
Output
[ vi j ai @l ocal host poi nt er ] $ gcc ptrvar.c
[ vi j ai @l ocal host poi nt er ] $ ./a.out
X val ue i s 125 and st or ed at 3221216452
Y val ue i s 23 and st or ed at 3221216448
I nt poi nt er hol ds t he addr ess 3221216452
Aceesi ng val ue t hr o poi nt er : 125
I nt poi nt er now hol ds t he addr ess 3221216448
Accessi ng val ue t hr o poi nt er : 23
Si ze of i nt poi nt er : 4 byt es
Si ze of f l oat poi nt er : 4 byt es
Addr ess of mai n f unct i on i s 134513448
3.1.CPointertoPointer
Algorithm
Step 1 : Demonstrate void pointer by making it to point to variables of different type
Step 2 : Declare a pointer variablep1 and assign a variable's address of its type
Step 3 : Declare a double pointer p2 and assign it the address of p1
Step 4 : Display the address stored inp1, data accessed usingp1 andp1's address
Step 5 : Display the address stored inp2, data accessed usingp2 andp2's address
Step 6 : Stop
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Program (ptrtoptr.c)
/ * Poi nt er var i abl es */
# i ncl ude<st di o. h>
mai n( )
{
i nt x=12, *p1, **p2;
f l oat z=8. 5;
voi d *pt r ; / * Gener i c poi nt er */
pt r = &x ; / * pt r poi nt s t o x ( i nt ) */
pt r = &z; / * pt r poi nt s t o y ( f l oat ) */
p1 = &x;
p2 = &p1; / * Poi nt er t o poi nt er */
pr i nt f ( "X val ue i s %d and st or ed at %u\ n", x, &x) ;
pr i nt f ( "\ nPoi nt er hol ds t he addr ess %u\ n", p1) ;
pr i nt f ( "Aceesi ng val ue t hr u poi nt er : %d\ n", *p1) ;
pr i nt f ( "Poi nt er i s st or ed at l ocat i on : %u\ n", &p1) ;
pr i nt f ( "\ nPoi nt er - t o- poi nt er hol ds t he addr ess %u\ n", p2) ;
pr i nt f ( "Accessi ng val ue t hr u pt r - t o- pt r : %d\ n", **p2) ;
pr i nt f ( "\ nSi ze of pt r - t o- pt r : %d byt es\ n", si zeof ( pt r ) ) ;
}
Output
[ vi j ai @l ocal host poi nt er ] $ gcc ptrtoptr.c
[ vi j ai @l ocal host poi nt er ] $ ./a.out
X val ue i s 12 and st or ed at 3221220804
Poi nt er hol ds t he addr ess 3221220804
Aceesi ng val ue t hr u poi nt er : 12
Poi nt er i s st or ed at l ocat i on : 3221220800
Poi nt er - t o- poi nt er hol ds t he addr ess 3221220800
Accessi ng val ue t hr u pt r - t o- pt r : 12
Si ze of pt r - t o- pt r : 4 byt es
3.1.DAddition using pointers
Algorithm
Step 1 : Start
Step 2 : Read the values of a andb
Step 3 : Assign the address of a andb tox andy
Step 4 : Sum the values at locations pointed byx and y and store inc
Step 5 : Print c
Step 6 : Stop
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Program (ptradd.c)
/ * Addi t i on oper at i ons usi ng poi nt er s */
#i ncl ude<st di o. h>
mai n( )
{
i nt a, b, c;
i nt *pa, *pb;
pa=&a;
pb=&b;
pr i nt f ( "Ent er val ues f or A and B : ") ;
scanf ( "%d%d", &a, &b) ;
c = *pa + *pb;
pr i nt f ( "Sum= %d\ n" , c) ;
}
Output
[ vi j ai @l ocal host poi nt er ] $ gcc ptradd.c
[ vi j ai @l ocal host poi nt er ] $ ./a.out
Ent er val ues f or A and B : 4 6
Sum= 10
3.1.EBasic Calculator
Algorithm
Step 1 : Start
Step 2 : Read the values of a andb
Step 3 : Assign the address of a andb to pointerspa andpb
Step 4 : Display a simple calculator menu
Step 5 : Based on user choice, perform arithmetic operations using pointer variables
Step 6 : Display the result
Step 7 : Stop
Program (ptrcalc.c)
/ * Ar i t hmet i c oper at i ons usi ng poi nt er s */
#i ncl ude<st di o. h>
mai n( )
{
i nt a, b, c;
i nt *pa, *pb;
char op;
pa=&a;
pb=&b;
pr i nt f ( "Basi c Cal cul at or ") ;
pr i nt f ( "\ n + Addi t i on") ;
pr i nt f ( "\ n - Subt r act i on") ;
pr i nt f ( "\ n * Mul t i pl i cat i on") ;
pr i nt f ( "\ n / Quot i ent ") ;
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
pr i nt f ( "\ n % Remai nder ") ;
pr i nt f ( "\ n x Qui t ") ;
pr i nt f ( "\ nEnt er oper at or : ") ;
scanf ( "%c", &op) ;
pr i nt f ( "Ent er t wo i nt eger s : ") ;
scanf ( "%d%d", &a, &b) ;
swi t ch ( op)
{
case ' +' :
c = *pa + *pb;
br eak;
case ' - ' :
c = *pa - *pb;
br eak;
case ' *' :
c = *pa * *pb;
br eak;
case ' / ' :
c = *pa / *pb;
br eak;
case ' %' :
c = *pa %*pb;
br eak;
def aul t :
exi t ( 0) ;
}
pr i nt f ( " %d %c %d = %d\ n", a, op, b, c) ;
}
Output
[ vi j ai @l ocal host poi nt er ] $ gcc ptrcalc.c
[ vi j ai @l ocal host poi nt er ] $ ./a.out
Basi c Cal cul at or
+ Addi t i on
- Subt r act i on
* Mul t i pl i cat i on
/ Quot i ent
%Remai nder
x Qui t
Ent er oper at or : +
Ent er t wo i nt eger s : 12 23
12 + 23 = 35
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 3.2 Pointer Programming
Aim
To study the advantages of using pointers in C programming.
Pointers & Function
Arguments passed to functions arepass by value i.e., a copy of value of the actual arguments
are passed. Therefore changes made to formal arguments are not reflected to actual
arguments. However, to have the actual arguments modified during process by another
function, then addresses of the arguments are passed, instead of values through pointers. This
is known aspass by reference. Another use of pointers in function is that an address could be
returned, known asreturn by reference.
Pointers & Arrays
Pointers can be used for efficient traversal of a given array. An array name by itself is a
pointer to the first element in the array. The address of first element of array X can be
expressed as either &X[0] or X. Thei+1
th
element is termed as &X[i] or X+i. The value of i is
referred to as offset. Thus a pointer can be assigned an array variable and array elements can
be accessed by altering the offset. Similarly for two-dimensional array, X
i+1,j+1
element could
be accessed as * (* (X +i) +j).
Pointers & Strings
A string variable alternatively can be declared as a character pointer type since string is
represented as an array of characters. The advantage is that length of the string need not be
known in advance. Strings could be processed using character pointer.
Pointers & Structures
A pointer variable can be assigned a structure as any other type. The members of a structure
are accessed using the indirect selection operator (- >). Self-referential structure is a structure
where one of its members is a pointer to the structure itself. Such structures are used to
implement data structures such as list and trees.
Result
Thus C programs using pointers were executed and its efficacy realized.
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
3.2.APass by value & reference
Algorithm
Step 1 : Define function swapval with parameters of type integer that swaps two
variables using a temporary variable.
Step 2 : Define functionswapref with parameters of typeinteger pointer that swaps two
variables using a temporary variable and pointer notation
Step 3 : In main function get values of two variables, saya andb
Step 4 : Call functionswapval witha andb as arguments (Call by value)
Step 5 : Print the values of a andb after function call.
Step 6 : Call functionswapref withaddress of a andb as arguments (Call by reference)
Step 7 : Print the values of a andb after function call.
Step 8 : Stop
Program (passbyref.c)
/ * Pass by val ue and r ef er ence */
#i ncl ude <st di o. h>
mai n( )
{
i nt a, b;
voi d swapval ( i nt , i nt ) ; / * Pass by r ef er ence */
voi d swapr ef ( i nt *, i nt *) ; / * Pass by val ue */
pr i nt f ( "Ent er t he val ues of A and B : ") ;
scanf ( "%d%d", &a, &b) ;
swapval ( a, b) ; / * Cal l by val ue */
pr i nt f ( "\ nVal ues af t er Pass by Val ue\ n" ) ;
pr i nt f ( "Val ue of A i s %d\ n", a) ;
pr i nt f ( "Val ue of B i s %d\ n", b) ;
swapr ef ( &a, &b) ; / * Cal l by r ef er ence */
pr i nt f ( "\ nVal ues af t er Pass by Ref er ence\ n") ;
pr i nt f ( "Val ue of A i s %d\ n", a) ;
pr i nt f ( "Val ue of B i s %d\ n", b) ;
}
voi d swapr ef ( i nt *x, i nt *y)
{
i nt t ;
t = *x;
*x = *y;
*y = t ;
}
voi d swapval ( i nt a, i nt b)
{
i nt t ;
t = a;
a = b;
b = t ;
}
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Output
[ vi j ai @l ocal host poi nt er ] $ gcc passbyref.c
[ vi j ai @l ocal host poi nt er ] $ ./a.out
Ent er t he val ues of A and B : 12 23
Val ues af t er Pass by Val ue
Val ue of A i s 12
Val ue of B i s 23
Val ues af t er Pass by Ref er ence
Val ue of A i s 23
Val ue of B i s 12
3.2.BReturn by reference
Algorithm
Step 1 : Define function big with parameters of type integer pointer that returns the
address of the biggest number using pointers (Return by reference)
Step 2 : In main function get values of two variables, saya andb
Step 3 : Call functionbig withaddress of a andb as arguments (Call by reference)
Step 4 : Print value stored at the address returned
Program (retbyref.c)
/ *Ret ur n by r ef er ence*/
#i ncl ude <st di o. h>
i nt * bi g( i nt * x, i nt * y)
{
i f ( *x > *y)
r et ur n x;
el se
r et ur n y;
}
mai n( )
{
i nt a, b;
i nt *p;
pr i nt f ( "Ent er t wo val ues : ") ;
scanf ( "%d%d", &a, &b) ;
p = bi g( &a, &b) ;
pr i nt f ( "Bi ggest i s %d\ n" , *p) ;
}
Output
[ vi j ai @l ocal host poi nt er ] $ gcc retbyref.c
[ vi j ai @l ocal host poi nt er ] $ ./a.out
Ent er t wo val ues : 3 7
Bi ggest i s 7
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
3.2.CSum of one-dimensional array
Algorithm
Step 1 : Declare an integer array and an integer pointer p.
Step 2 : Get array elements using a for loop
Step 3 : Assign starting address of the array top
Step 4 : Set up a loop
Step 4.1 : Display the elements value and address using *p andp
Step 4.2 : Add elements value to sum
Step 4.3 : Increment p by 1
Step 5 : Display sum
Step 6 : Stop
Program (array1d.c)
/ * Poi nt er s and one- di mensi onal ar r ays */
#i ncl ude <st di o. h>
mai n( )
{
i nt i , n, sum=0;
i nt x[ 25] , *p;
pr i nt f ( "Ent er number of el ement s : ") ;
scanf ( "%d", &n) ;
pr i nt f ( "Ent er Ar r ay el ement s : ") ;
f or ( i =0; i <n; i ++)
scanf ( "%d" , &x[ i ] ) ;
p = x; / * p poi nt s t o ar r ay x */
f or ( i =0; i <n; i ++)
{
pr i nt f ( "x[ %d] = %d st or ed at %u\ n", i , *p, p) ;
sum+= *p;
p++; / * Addr ess i ncr ement ed poi nt s t o next el ement */
}
pr i nt f ( "Sum= %d\ n ", sum) ;
}
Output
[ vi j ai @l ocal host poi nt er ] $ gcc array1d.c
[ vi j ai @l ocal host poi nt er ] $ ./a.out
Ent er number of el ement s : 5
Ent er Ar r ay el ement s : 12 23 34 45 56
x[ 0] = 12 st or ed at 3221218368
x[ 1] = 23 st or ed at 3221218372
x[ 2] = 34 st or ed at 3221218376
x[ 3] = 45 st or ed at 3221218380
x[ 4] = 56 st or ed at 3221218384
Sum= 170
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
3.2.DDisplaying a two-dimensional array
Algorithm
Step 1 : Declare a 2D integer array a with 3 rows and 3 columns and initialize it.
Step 2 : Set up a loop with indexi that iterates for rows.
Step 3 : Set up a loop for the column indexj that iterates for columns.
Step 4 : Display the element using pointer notation as *(*(a +i) +j))
Step 5 : Stop
Program (2darray.c)
/ * Poi nt er s and 2- di mensi onal ar r ay */
#i ncl ude <st di o. h>
mai n( )
{
i nt a[ 3] [ 3] ={{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
i nt i , j ;
f or ( i =0; i <3; i ++)
{
f or ( j =0; j <3; j ++)
{
pr i nt f ( "%4d" , *( *( a+i ) +j ) ) ;
}
pr i nt f ( "\ n") ;
}
}
Output
[ vi j ai @l ocal host poi nt er ] $ gcc 2darray.c
[ vi j ai @l ocal host poi nt er ] $ ./a.out
1 2 3
4 5 6
7 8 9
3.2.EString copy using pointers
Algorithm
Step 1 : Create functionstringcopy with two parameters of type character pointer
Step 2 : Set up a loop that iterates until thesource string encounters anull character
Step 2.1 : Assign thesource strings character to thedestination string
Step 2.2 : Increment the source and destination strings address by 1
Step 2.3 : Assignnull character to the destination string
Step 3 : Inmain function, declare two stringssrc anddest
Step 4 : Get a string from the user for src
Step 5 : Call stringcopy function and pass the address of src and dest
Step 6 : Displaydest string
Step 7 : Stop
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Program (strcopy.c)
/ * Copy st r i ngs usi ng poi nt er s */
#i ncl ude <st di o. h>
mai n( )
{
voi d st r i ngcopy( char *, char *) ;
char sr c[ 80] ;
char des[ 80] ;
pr i nt f ( "Ent er a st r i ng : ") ;
get s( sr c) ;
st r i ngcopy( des, sr c) ;
pr i nt f ( "Copi ed st r i ng : %s\ n", des) ;
}
voi d st r i ngcopy( char *d, char *s)
{
whi l e( *s)
{
*d = *s;
s++;
d++;
}
*d = ' \ 0' ;
}
Output
[ vi j ai @l ocal host poi nt er ] $ gcc strcopy.c
[ vi j ai @l ocal host poi nt er ] $ ./a.out
Ent er a st r i ng : Sel f - conquest i s t he gr eat est vi ct or y
Copi ed st r i ng : Sel f - conquest i s t he gr eat est vi ct or y
3.2.FStudent Detail
Algorithm
Step 1 : Declare astudent structure with membersrollno, name andmark
Step 2 : Create a variables1, and a pointer ptr of type student
Step 3 : Populates1 with inputs from the user
Step 4 : Assign address of s1 toptr
Step 5 : Display the values of structure members using pointer-to-member operator
Step 6 : Stop
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Program (studdetail.c)
#i ncl ude<st di o. h>
st r uct st udent
{
l ong r ol l no;
char name[ 10] ;
f l oat mar k;
};
mai n( )
{
st r uct st udent *pt r ;
st r uct st udent s1;
pr i nt f ( "\ nEnt er st udent s r ol l no, name, mar k : ") ;
scanf ( "%l d%s%f " , &s1. r ol l no, s1. name, &s1. mar k) ;
pt r =&s1;
pr i nt f ( "\ n\ t STUDENT DETAI L") ;
pr i nt f ( "\ nRol l no\ t Name\ t \ t Mar k\ n") ;
pr i nt f ( "%l d\ t %s\ t %. 2f \ n", pt r - >r ol l no, pt r - >name, pt r - >mar k) ;
}
Output
[ vi j ai @l ocal host poi nt er ] $ gcc studdetail.c
[ vi j ai @l ocal host poi nt er ] $ ./a.out
Ent er st udent s r ol l no, name, mar k : 1032957 Adhi t han 10
STUDENT DETAI LS
Rol l no Name Mar k
1032957 Adhi t han 10. 00
3.2.GEmployee Payroll
Algorithm
Step 1 : Declare aemployee structure with membersid, name, basic, hra, da, it, gross
andnetpay
Step 2 : Create array of structure employee asemp and a pointer ptr of type employee
Step 3 : Get number of employees as input
Step 4 : Set up a loop and for each employee obtain values for id, name andbasic
Step 5 : Set up a loop, and for each employee
Step 5.1 : Computehra, da, it as given in the problem statement
Step 5.2 : Computegross= hra + da
Step 5.3 : Computenetpay = gross - it
Step 6 : Display header for employee payroll
Step 7 : Assign address of emp toptr
Step 8 : Setup a loop and display employees data in a tabular format using ptr
Step 9 : Stop
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Program (payroll.c)
/ * Payr ol l Gener at i on */
#i ncl ude <st di o. h>
st r uct empl oyee
{
i nt empi d;
char ename[ 15] ;
i nt basi c;
f l oat hr a;
f l oat da;
f l oat i t ;
f l oat gr oss;
f l oat net pay;
};
mai n( )
{
st r uct empl oyee emp[ 50] , *pt r ;
i nt i , j , n;
pr i nt f ( "Ent er No. of Empl oyees : ") ;
scanf ( "%d" , &n) ;
f or ( i =0; i <n ; i ++)
{
pr i nt f ( " \ nEnt er Empl oyee Det ai l s\ n") ;
pr i nt f ( " Ent er Empl oyee I d : ") ;
scanf ( "%d", &emp[ i ] . empi d) ;
pr i nt f ( " Ent er Empl oyee Name : ") ;
scanf ( "%s", emp[ i ] . ename) ;
pr i nt f ( " Ent er Basi c Sal ar y : ") ;
scanf ( "%d", &emp[ i ] . basi c) ;
}
pt r =emp;
f or ( i =0; i <n; i ++)
{
pt r - >hr a = 0. 02 * pt r - >basi c;
pt r - >da = 0. 01 * pt r - >basi c;
pt r - >i t = 0. 05 * pt r - >basi c;
pt r - >gr oss = pt r - >basi c+pt r - >hr a+pt r - >da;
pt r - >net pay = pt r - >gr oss - pt r - >i t ;
pt r ++;
}
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
pt r =emp;
pr i nt f ( "\ n\ n\ n\ t \ t \ t \ t XYZ & Co. Payr ol l \ n\ n") ;
f or ( i =0; i <80; i ++)
pr i nt f ( " *") ;
pr i nt f ( " \ nEmpI d\ t Name\ t \ t Basi c\ t HRA\ t DA\ t I T\ t Gr oss\ t \ t Net Pay\ n\ n") ;
f or ( i =0; i <80; i ++)
pr i nt f ( " *") ;
f or ( i =0; i <n; i ++)
{
pr i nt f ( "\ n%d\ t %- 15s\ t %d\ t %. 2f \ t %. 2f \ t %. 2f \ t %. 2f \ t %. 2f ", pt r - >empi d,
pt r - >ename, pt r - >basi c, pt r - >hr a, pt r - >da, pt r - >i t , pt r - >gr oss, pt r - >net pay) ;
pt r ++;
}
pr i nt f ( "\ n") ;
f or ( i =0; i <80; i ++)
pr i nt f ( " *") ;
}
Output
[ vi j ai @l ocal host poi nt er ] $ gcc studdetail.c
[ vi j ai @l ocal host poi nt er ] $ ./a.out
Ent er No. of Empl oyees : 2
Ent er Empl oyee Det ai l s
Ent er Empl oyee I d : 436
Ent er Empl oyee Name : Gopal
Ent er Basi c Sal ar y : 10000
Ent er Empl oyee Det ai l s
Ent er Empl oyee I d : 463
Ent er Empl oyee Name : Raj esh
Ent er Basi c Sal ar y : 22000
XYZ & Co. Payr ol l
********************************************************************************
EmpI d Name Basi c HRA DA I T Gr oss Net Pay
********************************************************************************
436 Gopal 10000 200. 00 100. 00 500. 00 10300. 00 9800. 00
463 Raj esh 22000 440. 00 220. 00 1100. 00 22660. 00 21560. 00
********************************************************************************
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 3.3 Dynamic Memory Allocation
Aim
To achieve efficient memory utilization using dynamic memory allocation.
Memory allocated using arrays is insufficient or abundant, thereby inefficient. To overcome
this, memory could be allocated at run-time instead at compile time. The process of allocating
memory at run time is known as dynamic memory allocation. C inherently does not have this
facility but supports with memory management functions mal l oc, cal l oc andr eal l oc,
which can be used to allocate and free memory usingf r ee during the program execution.
The memory space located between program and local variable is available known as heap
for dynamic allocation during the execution of the program. The size of heap keeps changing
when program is executed due to creation and death of variables. Therefore it is possible to
encounter memory overflow during dynamic allocation process. In such situations, the
memory allocation functions will return a null pointer.
malloc
The malloc function reserves a block of memory of specified size and returns a pointer of
type void containing the first byte of the allocated region. Thus it could be casted to any type
of pointer. The allocated space contains garbage data.
ptr =( cast-type*) mal l oc( bytesize) ;
calloc
calloc is another memory allocation function that is normally used to request multiple blocks
of storage each of the same size and then sets all bytes to zero.
ptr =( casttype*) cal l oc( blockcount, blocksize) ;
free
Compile time storage of a variable is allocated and released by the system in accordance with
its storage class. With the dynamic runtime allocation, it is our responsibility to release the
space when it is not required, using the free function. The release of storage space becomes
important when the storage is limited.
f r ee( ptr) ;
realloc
The memory allocated by using calloc or malloc might be insufficient or excess sometimes.
In both the situations the memory size already allocated could be changed with the help of
function realloc. This process is called reallocation of memory.
ptr = r eal l oc( ptr, newsize) ;
Result
Thus memory requirements were allocated dynamically and released later.
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
3.3.AMark aggregate
Algorithm
Step 1 : Read number of students, sayn
Step 2 : Request memory dynamically to store marks of n students usingmalloc and store
the address ina
Step 3 : If requested block of memory is not allocated thenStop
Step 4 : Set up a loop and read array elementsa
i
Step 5 : Initializesum to 0
Step 6 : Set up a loop and array elementsa
i
tosum
Step 7 : Compute mark aggregate and display it
Step 8 : Release the requested memory
Step 9 : Stop
Program (dynalloc.c)
/ * Dynami c Memor y Al l ocat i on usi ng mal l oc( ) */
#i ncl ude <st dl i b. h>
#i ncl ude <mal l oc. h>
#i ncl ude <st di o. h>
mai n( )
{
i nt n, i , *a;
f l oat avg, sum=0;
pr i nt f ( "Ent er t he No. of st udent s : ") ;
scanf ( "%d" , &n) ;
a = ( i nt *) mal l oc( n * si zeof ( i nt ) ) ;
i f ( a == NULL)
{
pr i nt f ( "\ n memor y al l ocat i ons not possi bl e") ;
exi t ( - 1) ;
}
pr i nt f ( "Ent er %d mar ks : ", n) ;
f or ( i =0; i <n; i ++)
{
scanf ( "%d" , &a[ i ] ) ;
}
f or ( i =0; i <n; i ++)
sum+= a[ i ] ;
avg = sum/ n;
pr i nt f ( "Aver age mar k : %. 2f \ n", avg) ;
f r ee( a) ;
}
Output
[ vi j ai @l ocal host poi nt er ] $ gcc dynalloc.c
[ vi j ai @l ocal host poi nt er ] $ ./a.out
Ent er t he No. of st udent s : 6
Ent er 6 mar ks : 56 67 78 89 90 98
Aver age mar k : 79. 67
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
3.3.BString Reallocation
Algorithm
Step 1 : Declare a stringbuf andmessage of type character pointer
Step 2 : Obtain text for buf from the user
Step 3 : Request memory allocation for message based on length(buf) +1 usingmalloc
Step 4 : Copy contents of buf tomessage
Step 5 : Displaymessage and its capacity
Step 6 : Obtain another text for buf from the user
Step 9 : Request memory reallocation for message based on length(buf) +1 usingrealloc
Step 11 : Copy contents of buf tomessage
Step 12 : Displaymessage and its capacity
Step 13 : Release the requested memory and Stop
Program (strrealloc.c)
/ * Dynami c Real l ocat i on f or st r i ngs */
#i ncl ude <st di o. h>
#i ncl ude <st dl i b. h>
#i ncl ude <st r i ng. h>
mai n( )
{
char buf [ 80] , *message;
pr i nt f ( "Ent er t ext and pr ess ent er : ") ;
get s( buf ) ; / * Get a st r i ng f r omt he user */
/ * Al l ocat e t he i ni t i al bl ock and copy t he st r i ng t o i t . */
message = ( char *) mal l oc( st r l en( buf ) +1) ;
st r cpy( message, buf ) ;
pr i nt f ( "Cont ent st or ed i s : ") ;
put s( message) ; / * Di spl ay t he message. */
pr i nt f ( "I ni t i al al l ocat i on : %d byt es\ n" , st r l en( message) ) ;
pr i nt f ( "Ent er anot her t ext and pr ess ent er : ") ;
get s( buf ) ; / * Get anot her st r i ng f r omt he user . */
/ * Real l ocat e f or t he new st r i ng */
message = ( char *) r eal l oc( message, st r l en( buf ) + 1) ;
st r cpy( message, buf ) ;
pr i nt f ( "Modi f i ed cont ent i s : ") ;
put s( message) ; / * Di spl ay t he new message. */
pr i nt f ( "Real l ocat ed memor y : %d byt es\ n" , st r l en( message) ) ;
f r ee( message) ;
}
Output
[ vi j ai @l ocal host poi nt er ] $ gcc strrealloc.c
[ vi j ai @l ocal host poi nt er ] $ ./a.out
Ent er t ext and pr ess ent er : Hi !
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Cont ent st or ed i s : Hi !
I ni t i al al l ocat i on : 4 byt es
Ent er anot her t ext and pr ess ent er : How r u?
Modi f i ed cont ent i s : How r u?
Real l ocat ed memor y : 8 byt es
3.3.CAllocation for two dimensional array
Algorithm
Step 1 : Declare a pointer-to-pointer ptr variable
Step 2 : Get number of rows andcols
Step 3 : Request memory for ptr based onrows usingcalloc (Array of pointers)
Step 4 : Set up a loop that iterates based onrows
Step 4.1 : Request memory for each array element of ptr based oncols using calloc
Step 5 : Set up a nested loop and display the 2D array with default values
Step 6 : Release the requested memory and Stop
Program (2dcalloc.c)
/ * Dynami c al l ocat i on f or 2D ar r ay */
#i ncl ude <st di o. h>
#i ncl ude <mal l oc. h>
mai n( )
{
i nt i , j , r ow, col , **pt r ;
pr i nt f ( "Ent er r ow and col umn di mensi on : ") ;
scanf ( "%d%d", &r ow, &col ) ;
/ * 2d ar r ay i s an ar r ay of poi nt er s */
pt r = ( i nt *) cal l oc( r ow, si zeof ( i nt ) ) ;
f or ( i =0; i <r ow; i ++)
pt r [ i ] = ( i nt *) cal l oc( col , si zeof ( i nt ) ) ;
/ * Di spl ay def aul t val ue 0 assi gned due t o cal l oc */
f or ( i =0; i <r ow; i ++)
{
f or ( j =0; j <col ; j ++)
pr i nt f ( "%4d" , pt r [ i ] [ j ] ) ;
pr i nt f ( "\ n") ;
}
f r ee( pt r ) ;
}
Output
[ vi j ai @l ocal host poi nt er ] $ gcc 2dcalloc.c
[ vi j ai @l ocal host poi nt er ] $ ./a.out
Ent er r ow and col umn di mensi on : 3 4
0 0 0 0
0 0 0 0
0 0 0 0
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 3.4 File Handling
Aim
To perform disk I/O using file handling
Many application require information stored on auxillary storage device. Such
information is stored permanently as a data file that allows to access and alter the information
whenever necessary.
Opening a File
Prior to performing any activity of a file, the file should be opened. By opening a file, link
between the program and the operating system is established. This link exists by means of a
structure named FI LE, in header file stdio.h. Therefore, it is mandatory for programs
pertaining to file should include <stdio.h>.
When a request is made for a file to be opened, the operating system returns a pointer
to the structure FILE. The pointer is declared as
FI LE *fileptr;
A file is opened using the standard function fopen(). The file to be opened is searched
in the disk. If a file could not be opened, aNULL is returned.
fileptr =f open(" filename" , "mode");
The file mode specifies the purpose of opening a file. Some of them are
Mode Description
r Open an existing file for reading only
w Open a new file for writing only. If the file exists, its contents are destroyed
a Open an existing file for appending. If the file doesn't exist, a new file is created
The I/O operation is done using any of the following functions.
getc & putc
Thegetc function is used to read a character from the file opened in read mode and assigns it
to a character variable. The getc will return anEOF marker when the end-of-file is reached.
Thereafter reading is not possible. The putc function writes the character contained in the
variable onto a file opened in write mode. The file pointer moves by one character position
for every character I/O operation.
charvar =get c( fileptr) ;
put c( charvar, fileptr);
fgets & fputs
Rather than single characters, to deal with stringsfgets andfputs are used in a similar manner.
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
fscanf & fprintf
These functions handle mixed data. Care should be taken that the same format specifications
is used for both read and write operation.
fwrite & fread
Applications might perform I/O as blocks of data, where each block is a fixed number of
contiguous bytes. A block is generally represented as a structure. The library functions fread
and fwrite are intended to be used in situations of this type and requires arguments namely
address, size and number of the data block. fread reads a block of data and assigns to a
structure variable. fwrite writes contents of a structure variable onto the file.
f r ead( &structvar, si zeof ( structvar) , 1, fileptr) ;
f wr i t e( &structvar, si zeof ( structvar) , 1, fileptr) ;
Random Access
In random access any specified part of the file is pointed without the mundane reading
through the file upto that point. This is achieved with the help of functions fseek, ftell and
rewind available in the I/O library.
Function Description
f t el l Returns the number of bytes read or written
r ewi nd Resets the file pointer to start of the file
f seek Moves the file pointer to the desired byte
f seek( fileptr, offset, position) ;
position can take values 0, 1 or 2 indicatingbegining, current position, andend
of the file respectively
Fclose
A file should be closed when all operation on it have been completed. This ensures all
information associated with the file is flushed out of the buffers and all links to the file
broken. A file must be closed if the same should be opened in a different mode.
f cl ose( fileptr) ;
Result
Thus sequential and random disk I/O is executed using file handling functions.
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
3.4.AWrite to a file character-by-character
Algorithm
Step 1 : Declare a file pointer fp
Step 2 : Open fileCharFile.txt inwrite mode usingfp
Step 3 : If file could not be created then Stop
Step 4 : Read a character from the console
Step 5 : If character is not end-of-file then write it onto file usingputc
Step 6 : Repeat steps 4 and 5until end-of-file is encountered
Step 7 : Close the file
Step 8 : Stop
Program (chario.c)
/ * Fi l e I / O usi ng get c and put c f unct i ons */
#i ncl ude <st di o. h>
#i ncl ude <st dl i b. h>
mai n( )
{
FI LE *f p;
char c;
f p=f open( " Char Fi l e. t xt ", "w") ;
i f ( f p == NULL) {
pr i nt f ( "Fi l e not Accessi bl e") ;
exi t ( - 1) ;
}
pr i nt f ( "I nput Text - - Ct r l + D t o Ter mi nat e\ n") ;
/ * Get dat a ( char by char ) f r omuser and wr i t e ont o f i l e*/
whi l e( ( c=get char ( ) ) ! = EOF)
put c( c, f p) ;
f cl ose( f p) ;
}
Output
[ vi j ai @l ocal host f i l es] $ gcc chario.c
[ vi j ai @l ocal host f i l es] $ ./a.out
I nput Text - - Ct r l + D t o Ter mi nat e
Wel come t o Fi l e handl i ng
A f i l e shoul d be opened bef or e an I / O
I / O shoul d not conf l i ct wi t h t he mode
Af t er I / O f i l es shoul d be cl osed
[ vi j ai @l ocal host f i l es] $ cat CharFile.txt
Wel come t o Fi l e handl i ng
A f i l e shoul d be opened bef or e an I / O
I / O shoul d not conf l i ct wi t h t he mode
Af t er I / O f i l es shoul d be cl osed
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
3.4.BFile Statistics
Algorithm
Step 1 : Declare a file pointer fp and static variables lc, wc, cc
Step 2 : Open fileCharFile.txt inread mode usingfp
Step 3 : Fetch a character from the file
Step 4 : Display the character and increment cc by 1
Step 5 : If character is a newline then increment lc andwc by 1
Step 6 : If character is a whitespace then increment wc by 1
Step 7 : Repeat steps 36until end-of-file is encountered
Step 8 : Display number of words, lines and characters in the file
Step 9 : Close the file and Stop
Program (filestat.c)
/ * St at i st i cs of f i l e- wor d, l i nes, char act er */
#i ncl ude <st di o. h>
mai n( )
{
FI LE *f p;
char c;
st at i c i nt l c, wc, cc;
/ * Fi l e Read and pr ocess */
f p=f open( " Char Fi l e. t xt ", "r ") ;
whi l e( ( c=get c( f p) ) ! = EOF ) / * Pr ocess char - by- char */
{
swi t ch( c) / * Count l i nes, wor ds & char act er */
{
case ' \ n' :
++l c;
++wc;
br eak;
case ' ' :
++wc;
br eak;
def aul t :
++cc;
}
}
pr i nt f ( "No. of l i nes : %d", l c) ;
pr i nt f ( "\ nNo. of wor ds : %d", wc) ;
pr i nt f ( "\ nNo. of char act er s ( spaces excl . ) : %d\ n", cc) ;
f cl ose( f p) ;
}
Output
[ vi j ai @l ocal host f i l es] $ gcc filestat.c
[ vi j ai @l ocal host f i l es] $ ./a.out
No. of l i nes : 4
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
No. of wor ds : 25
No. of char act er s ( spaces excl . ) : 109
3.4.CEmployee Record
Algorithm
Step 1 : Declare structureemployee with memberscode, name, design andbasic
Step 2 : Declare a file pointer fp andvariablescasual of type employee
Step 3 : Open fileemp.dat inwrite mode usingfp
Step 4 : Set up a loop to input employee data until name='xxx'
Step 4.1 : Get full details of an employee usingcasual with code auto-generated
Step 4.2 : Writecasual onto fileemp.dat usingfwrite
Step 5 : Displaysize of the file usingftell andclose it
Step 6 : Reopen fileemp.dat inread mode usingfp
Step 7 : Get the employee code for which details are sought.
Step 8 : Go to the start of the required data usingfseek
Step 9 : Load the employee details onto casual usingfread and display it
Step 10 : Close the file and Stop
Program (emprec.c)
/ * Bi nar y I / O usi ng f wr i t e and r andomf r ead */
#i ncl ude <st di o. h>
#i ncl ude <st r i ng. h>
st r uct empl oyee
{
i nt code;
char name[ 20] ;
char desi g[ 20] ;
f l oat basi c;
};
mai n( )
{
st r uct empl oyee casual , t emp;
FI LE *f p;
i nt i d, eno, n, pos, l b;
i d = 1000;
f p = f open( "Emp. dat " , "w") ;
pr i nt f ( "\ t Ent er empl oyee det ai l s\ n" ) ;
whi l e ( 1)
{
casual . code=i d++;
pr i nt f ( "Empl oyee I d : %d" , casual . code) ;
pr i nt f ( "\ nEnt er Name ( xxx t o qui t ) : ") ;
scanf ( "%s" , casual . name) ;
i f ( st r cmp( casual . name, "xxx") == 0)
br eak;
pr i nt f ( "Ent er Desi gnat i on : ") ;
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
scanf ( "%s" , casual . desi g) ;
pr i nt f ( "Ent er Basi c Sal ar y: ") ;
scanf ( "%f " , &casual . basi c) ;
f wr i t e ( &casual , si zeof ( casual ) , 1, f p) ;
}
n = f t el l ( f p) ;
pr i nt f ( "\ nFi l e si ze : %d byt es\ n", n) ;
f cl ose( f p) ;
/ * Recor d seek */
f p = f open( "Emp. dat " , "r ") ;
pr i nt f ( "\ nEnt er Empl oyee i d : ") ;
scanf ( "%d" , &eno) ;
pos = ( eno- 1000) *si zeof ( casual ) ;
i f ( pos < n)
{
f seek( f p, pos, 0) ;
f r ead ( &t emp, si zeof ( t emp) , 1, f p) ;
pr i nt f ( "Empl oyee Name : %s\ n", t emp. name) ;
pr i nt f ( "Empl oyee Desi gnat i on : %s\ n", t emp. desi g) ;
pr i nt f ( "Empl oyee Basi c : %. 2f \ n", t emp. basi c) ;
}
el se
pr i nt f ( "\ nI ncor r ect Empl oyee I d") ;
f cl ose( f p) ;
}
Output
Ent er empl oyee det ai l s
Empl oyee I d : 1000
Ent er Name ( xxx t o qui t ) : Pr abakhar
Ent er Desi gnat i on : Anal yst
Ent er Basi c Sal ar y: 34000
Empl oyee I d : 1001
Ent er Name ( xxx t o qui t ) : Raghu
Ent er Desi gnat i on : Admi ni st r at or
Ent er Basi c Sal ar y: 28000
Empl oyee I d : 1002
Ent er Name ( xxx t o qui t ) : Gokul
Ent er Desi gnat i on : Pr ogr ammer
Ent er Basi c Sal ar y: 25000
Ent er Name ( xxx t o qui t ) : xxx
Fi l e si ze : 150 byt es
Ent er Empl oyee i d : 1001
Empl oyee Name : Raghu
Empl oyee Desi gnat i on : Admi ni st r at or
Empl oyee Basi c : 28000. 00
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 3.5 Command Line Arguments
Aim
To study the use of command line arguments
Command-line arguments are given after the name of a program in command-line operating
systems like DOS or Linux, and are passed in to the program from the operating system.
In C, main function can accept two arguments: one argument is number of command line
arguments, and the other argument is a list of all of the command line arguments.
mai n( i nt ar gc, char *ar gv[ ] )
The first one integer, (conventionally called argc) is the argument count. It is the number of
arguments passed into the program from the command line, including the name of the
program.
The second is a pointer to an array of character strings (conventionally called argv), for
argument vector that contains the arguments, one per string. argv[0] is the name of the
program. After that, every element number less than argc is a command line argument.
argv[argc] is a null pointer.
C's model of command line arguments adheres to the following:
Arguments are delimited by white space, which is either a space or a tab.
A string surrounded by double quotation marks is interpreted as a single argument.
A double quotation mark preceded by a backslash, \", is interpreted as".
Two back slashe (\\) is replaced by a single backslash (\).
For instance, the following command line is interpreted as
$. / copy cnot es cpnot es
argc =3
argv[0] =./copy
argv[1] =cnotes
argv[2] =cpnotes
Command line arguments are typically used to pass the name of a data file to an application.
Programs containing command line parameters are generally used to imitate OS commands.
Result
Thus arguments were passed to programs at command line and executed
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
3.5.AListing command line arguments
Program (cmdline.c)
/ * Command l i ne ar gument s */
#i ncl ude <st di o. h>
mai n( i nt ar gc, i nt *ar gv[ ] )
{
i nt i ;
pr i nt f ( "Number of ar gument s : %d\ n" , ar gc) ;
f or ( i =0; i <ar gc; i ++)
pr i nt f ( "Ar gument [ %d] = %s\ n", i , ar gv[ i ] ) ;
}
Output
[ vi j ai @l ocal host f i l es] $ gcc cmdline.c -o cmdline
[ vi j ai @l ocal host f i l es] $ ./cmdline "C:\\Program Files\\Adobe" readme.txt
Number of ar gument s : 3
Ar gument [ 0] = . / cmdl i ne
Ar gument [ 1] = C: \ Pr ogr amFi l es\ Adobe
Ar gument [ 2] = r eadme. t xt
3.5.BFile copy
Program (filecopy.c)
/ * Fi l e copyi mi t at i ng cp command */
#i ncl ude <st di o. h>
#i ncl ude <st dl i b. h>
mai n( i nt ar gc, char *ar gv[ ] ) / * Command l i ne ar gument s */
{
FI LE *sr c, *des;
char ch;
i f ( ar gc ! = 3)
{
pr i nt f ( "Ar gument s i nsuf f i ci ent \ n") ;
pr i nt f ( "Usage : . / f i l ecopy sour ce dest \ n") ;
exi t ( - 1) ;
}
sr c = f open( ar gv[ 1] , "r ") ;
i f ( sr c==NULL )
{
pr i nt f ( "Sour ce Fi l e not Acccessi bl e\ n") ;
exi t ( - 1) ;
}
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
des = f open( ar gv[ 2] , "w") ;
i f ( des==NULL)
{
pr i nt f ( "Unabl e t o cr eat e Dest i nat i on f i l e\ n") ;
exi t ( - 1) ;
}
whi l e ( 1)
{
ch=get c( sr c) ;
i f ( ch==EOF)
br eak;
el se
put c( ch, des) ;
}
pr i nt f ( "Fi l e Copi ed\ n") ;
f cl ose( sr c) ;
f cl ose( des) ;
}
Output
[ vi j ai @l ocal host f i l es] $ gcc filecopy.c -o filecopy
[ vi j ai @l ocal host f i l es] $ . / f i l ecopy Random. t xt
Ar gument s i nsuf f i ci ent
Usage : . / f i l ecopy sour ce dest
[ vi j ai @l ocal host f i l es] $ ./filecopy Random.txt r.txt
Fi l e Copi ed
[ vi j ai @l ocal host f i l es] $ l s
a. out char i o. c cmdl i ne. c empr ec. c f i l ecopy. c r andom. c r . t xt
Char Fi l e. t xt cmdl i ne Empl oyee. t xt f i l ecopy f i l est at . c Random. t xt
[ vi j ai @l ocal host f i l es] $ cmp Random. t xt r . t xt
[ vi j ai @l ocal host f i l es] $
3.5.CDisplay file contents
Program (filecat.c)
/ * Cat command */
#i ncl ude <st di o. h>
mai n( i nt ar gc, char *ar gv[ ] )
{
FI LE *f p;
char c;
i f ( ar gc ! = 2)
{
f pr i nt f ( st der r , "I nsuf f i ci ent ar gument s\ n") ;
f pr i nt f ( st der r , "Usage: . / f i l ecat f i l ename\ n" ) ;
exi t ( - 1) ;
}
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
f p = f open( ar gv[ 1] , "r ") ;
i f ( f p == NULL)
{
f pr i nt f ( st der r , "cat : can' t open %s\ n", ar gv[ 1] ) ;
exi t ( - 1) ;
}
whi l e( ( c = get c( f p) ) ! = EOF)
put char ( c) ;
f cl ose( f p) ;
}
Output
[ vi j ai @l ocal host f i l es] $ gcc filecat.c -o filecat
[ vi j ai @l ocal host f i l es] $ . / f i l ecat
I nsuf f i ci ent ar gument s
Usage: . / f i l ecat f i l ename
[ vi j ai @l ocal host f i l es] $ . / f i l ecat char f i l e. t xt
cat : can' t open char f i l e. t xt
[ vi j ai @l ocal host f i l es] $ ./filecat CharFile.txt
Wel come t o Fi l e handl i ng
A f i l e shoul d be opened bef or e an I / O
I / O shoul d not conf l i ct wi t h t he mode
Af t er I / O f i l es shoul d be cl osed