ge 2155 full

154
GE2155 COMPUTER PRACTICE LABORATORY – II L T P C 0 1 2 2 SYLL A BUS 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 un

Upload: ramkumar-sivakaminathan

Post on 10-Nov-2014

61 views

Category:

Documents


5 download

DESCRIPTION

GE2155 LAB MANUAL

TRANSCRIPT

Page 1: Ge 2155 Full

GE2155 COMPUTER PRACTICE LABORATORY – II L T P C0 1 2 2

SYLL A BUS

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 PERIODSun

Page 2: Ge 2155 Full

T ABLE OF C ONTEN T S

Ex. No Lab # Name of the experiment Page No

1 BASIC UNIX COMMANDS

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

COMMAND MODE

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 TWO VALUES

B CENTIGRADE TO FAHRENHEIT

C AREA OF A CIRCLE

D SIMPLE INTEREST

2.2 7 DECISION MAKING

A ODD OR EVEN

B BIGGEST OF 3 NUMBERS

C LEAP YEAR

Page 3: Ge 2155 Full

Ex. No Lab # Name of the experiment Page No

D GRADE DETERMINATION

E EMPLOYEE PAY

F STRING COMPARISON

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 MULTIPLICATION TABLE

B ARMSTRONG NUMBER

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 BASED GREET

B MONTH DAYS

C COMMAND MENU

D DIRECTORY LISTING

E FILE TYPE

F FILE DUPLICATES

G DETECT USER LOGON

H COMPILE & EXECUTE

3 C PROGRAMMING

3.1 11 INTRODUCTION TO POINTERS

A REFERENCE & DEREFERENCE

B POINTER VARIABLES

C POINTER TO POINTER

D ADDITION USING POINTERS

Page 4: Ge 2155 Full

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 PRINTING 2D ARRAY

E STRING COPY

F STUDENT DETAILS

G PAYROLL PROCESSING

3.3 13 DYNAMIC MEMORY ALLOCATION

A MARK AGGREGATE

B STRING REALLOCATION

C 2D ARRAY ALLOCATION

3.4 14 FILE HANDLING

A WRITE TO FILE—CHARACTER I/O

B FILE STATISTICS

C EMPLOYEE FILE—RANDOM ACCESS

3.5 15 COMMAND LINE ARGUMENTS

A ARGUMENT LIST

B FILE COPY—CP

C FILE DISPLAY—CAT

Page 5: Ge 2155 Full

Unix Commands GE2155–Computer Practice II

Ex. No: 1.1 STUDY OF UNIX OPERATING SYSTEM

AIM

To introduce the concept of UNIX Operating System

OPERATING SYSTEM

An Operating System is a set of programs that

x Functions as an virtual machine by presenting an interface that is easier to program than the underlying hardware

x 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 User—The system will have its own hard disk, memory, CPU and other resources all dedicated to a single user. Eg. MS-DOS

2. Multi User—The 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

UNIX HISTORY

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 in1973 in C principally authored by Ritchie.

UNIX FEATURES

1. Multi-user system—Multi-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 system—Multitasking is the capability of the operating system to perform various task simultaneously, i.e. a user can run multiple tasks concurrently.

3. Programming Facility—UNIX is highly programmable, the UNIX shell has all the necessary ingredients like conditional and control structures, etc.

4. Security—UNIX allows sharing of data; every user must have a single login name and password. So, accessing another user’s data is impossible without his permission.

5. Portability—UNIX is portable because it is written in a high level language. So, UNIX can be run on different computers.

Page 6: Ge 2155 Full

Unix Commands GE2155–Computer Practice II

6. Communication—UNIX 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 andLibraries and enhanced GUI (X Window).

ORGANIZATION OF UNIX

The UNIX system is functionally organized at three levels and are:

1. The kernel, which schedules tasks and manages storage;

2. The shell, which connects and interprets users' commands, calls programs from memory, and executes them; and

3. The tools 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.

Page 7: Ge 2155 Full

Unix Commands GE2155–Computer Practice II

FILE SYSTEM

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 files—Contains stream of data. All data, text, source programs, object and executable code, commands fall into this category.

¾ Directory files—Contains 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 files—Even 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.

Page 8: Ge 2155 Full

Unix Commands GE2155–Computer Practice II

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.

To logon, type telnet server_ipaddress in run 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 FunctionDate Used to display the current system date and time.date +%D Displays date only

date +%T Displays time onlydate +% Y Displays the year part of datedate +% H Displays the hour part of timeCal Calendar of the current monthcal year Displays calendar for all months of the specified yearcal month year Displays calendar for the specified month of the yearWho Login details of all users such as their IP, Terminal No, User name,who am i Used to display the login details of the userTty Used to display the terminal nameuname Displays the Operating Systemuname –r Shows version number of the OS (kernel).uname –n Displays domain name of the serverecho "txt" Displays the given text on the screenecho $HOME Displays the user's home directoryBc Basic calculator. Press Ctrl+d to quitlp file Allows the user to spool a job along with others in a print queue.man cmdname Manual for the given command. Press q to exithistory To display the commands used by the user since log on.Exit Exit from a process. If shell is the only process then logs out

Directory commands

Command FunctionPwd Path of the present working directorymkdir dir A directory is created in the given name under the current directorymkdir dir1 dir2 A number of sub-directories can be created under one strokecd 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.

Page 9: Ge 2155 Full

Unix Commands GE2155–Computer Practice II

Command Functioncd .. To move back to the parent directoryrmdir subdir Removes an empty sub-directory.

File commands

Command Functioncat > 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 filecp src des Copy files to given location. If already exists, it will be overwrittencp –i src des Warns the user prior to overwriting the destination filecp –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 usedmv 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.rm file Used to delete a file or group of files. –i option can also be usedrm * To delete all the files in the directory.rm –r * Deletes all files and sub-directoriesrm –f * To forcibly remove even write-protected filesLs Lists all files and subdirectories (blue colored) in sorted manner.ls name To check whether a file or directory exists.ls name* Short-hand notation to list out filenames of a specific pattern.ls –a Lists all files including hidden files (files beginning with .)ls –x dirname To have specific listing of a directory.ls –R Recursive listing of all files in the subdirectoriesls –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 command exit or logout.

Result

Thus the stud y and execution of Unix commands has been completed successfully.

Page 10: Ge 2155 Full

Unix Commands GE2155–Computer Practice II

[v i jai@ l ocal h os t vijai]$ dateSat Apr 9 13:03:47 IST 2011

[v i jai@ l ocal h os t vijai]$ date +%D04/09/11

[v i jai@ l ocal h os t vijai]$ date +%T13:05:33

[v i jai@ l ocal h os t vijai]$ date +%Y2011

[v i jai@ l ocal h os t vijai]$ date +%H13

[v i jai@ l ocal h os t vijai]$ calApril 2011

Su Mo Tu We Th Fr Sa1 2

3 4 5 6 7 8 910 11 12 13 14 15 1617 18 19 20 21 22 2324 25 26 27 28 29 30

[v i jai@ l ocal h os t vijai]$ cal 08 1998August 1998

Su Mo Tu We Th Fr Sa1

2 3 4 5 6 7 89 10 11 12 13 14 15

16 17 18 19 20 21 2223 24 25 26 27 28 2930 31

[v i jai@ l ocal h os t vijai]$ cal 18001800

January February MarchSu 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 15 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 1519 20 21 22 23 24 25 16 17 18 19 20 21 22 16 17 18 19 20 21 2226 27 28 29 30 31 23 24 25 26 27 28 23 24 25 26 27 28 29

30 31… … … October

November DecemberSu 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 65 6 7 8 9 10 11 2 3 4 5 6 7 8 7 8 9 10 11 12 13

Page 11: Ge 2155 Full

Unix Commands GE2155–Computer Practice II

12 13 14 15 16 17 18 9 10 11 12 13 14 15 14 15 16 17 18 19 2019 20 21 22 23 24 25 16 17 18 19 20 21 22 21 22 23 24 25 26 2726 27 28 29 30 31 23 24 25 26 27 28 29 28 29 30 31

30

[vi jai@l ocalh ost vijai]$ whoRoot :0 Apr 9 08:41Vijai pts/0 Apr 9 13:00 (scl-64)cse1 pts/3 Apr 9 13:18 (scl-41.smkfomra.com)Ecea pts/4 Apr 9 13:18 (scl-29.smkfomra.com)

[v i jai@ l ocal h os t vijai]$ who am ivijai pts/0 Apr 9 13:00 (scl-64)

[v i jai@ l ocal h os t vijai]$ tty/dev/pts/0

[v i jai@ l ocal h os t vijai]$ unameLinux

[v i jai@ l ocal h os t vijai]$ uname -r2.4.20-8smp

[v i jai@ l ocal h os t vijai]$ uname -nlocalhost.localdomain

[v i jai@ l ocal h os t vijai]$ echo "How are you"How are you

[v i jai@ l ocal h os t vijai]$ echo $HOME/home/vijai

[v i jai@ l ocal h os t vijai]$ echo $USERvijai

[v i jai@ l ocal h os t vijai]$ bcbc 1.06Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.3+582%32

[v i jai@ l ocal h os t loops]$ pwd/home/vijai/shellscripts/loops

[v i jai@ l ocal h os t vijai]$ mkdir filter[v i jai@ l ocal h os t vijai]$ lsfilter list.sh regexpr shellscripts

Page 12: Ge 2155 Full

Unix Commands GE2155–Computer Practice II

[v i jai@ l ocal h os t vijai]$ cd shellscripts/loops/[v i jai@ l ocal h os t loops]$

[v i jai@ l ocal h os t loops]$ cd[v i jai@ l ocal h os t vijai]$

[v i jai@ l ocal h os t loops]$ cd /[v i jai@ l ocal h os t /]$

[v i jai@ l ocal h os t /]$ cd /home/vijai/shellscripts/loops/[v i jai@ l ocal h os t loops]$ cd ..[v i jai@ l ocal h os t shellscripts]$

[v i jai@ l ocal h os t vijai]$ rmdir filter[v i jai@ l ocal h os t vijai]$ lslist.sh regexpr shellscripts

[v i jai@ l ocal h os t vijai]$ cat > greethi ece-awishing u the best[v i jai@ l ocal h os t vijai]$ cat greethi ece-awishing u the best

[v i jai@ l ocal h os t vijai]$ cat >> greetbye

[v i jai@ l ocal h os t vijai]$ cat greethi ece-awishing u the best bye

[v i jai@ l ocal h os t vijai]$ lsgreet list.sh regexpr shellscripts

[vi jai@l ocalh ost vijai]$ ls -a. .bash_logout .canna .gtkrc regexpr .viminfo.tmp.. .bash_profile .emacs .kde shellscripts .xemacs.bash_history .bashrc greet list.sh .viminfo

[v i jai@ l ocal h os t vijai]$ ls -ltotal 16-rw-rw-r-- 1 vijai vijai 32 Apr 11 14:52 greet-rw-rw-r-- 1 vijai vijai 30 Apr 4 13:58 list.shdrwxrwxr-x 2 vijai vijai 4096 Apr 9 14:30 regexprdrwxrwxr-x 7 vijai vijai 4096 Apr 4 14:57 shellscripts

[v i jai@ l ocal h os t vijai]$ cp greet ./regexpr/[vi jai@l ocalh ost vijai]$ ls

Page 13: Ge 2155 Full

Unix Commands GE2155–Computer Practice II

greet list.sh regexpr shellscripts

[v i jai@ l ocal h os t vijai]$ ls ./regexpr demo greet

[v i jai@ l ocal h os t vijai]$ cp -i greet ./regexpr/cp: overwrite 'greet'? n

[v i jai@ l ocal h os t vijai]$ mv greet greet.txt[v i jai@ l ocal h os t vijai]$ lsgreet.txt list.sh regexpr shellscripts

[v i jai@ l ocal h os t vijai]$ mv greet.txt ./regexpr/[v i jai@ l ocal h os t vijai]$ ls list.sh

regexpr shellscripts [v i jai@ l ocal h os t vijai]$ ls ./regexpr/ demo greet.txt

[v i jai@ l ocal h os t vijai]$ lsfact.sh list.sh prime.sh regexpr shellscripts[v i jai@ l ocal h os t vijai]$ rm -i *.sh rm: remove regular file 'fact.sh'? y rm: remove regular file 'list.sh'? n rm: remove regular file 'prime.sh'? y

[v i jai@ l ocal h os t vijai]$ lslist.sh regexpr shellscripts

[v i jai@ l ocal h os t vijai]$ wc list.sh4 9 30 list.sh

[v i jai@ l ocal h os t vijai]$ wc -l list.sh4 list.sh

[v i jai@ l ocal h os t vijai]$ cmp list.sh fact.shlist.sh fact.sh differ: byte 1, line 1

[v i jai@ l ocal h os t vijai]$ ls -l list.sh-rw-rw-r-- 1 vijai vijai 30 Apr 4 13:58 list.sh

[v i jai@ l ocal h os t vijai]$ chmod ug+x list.sh [v i jai@ l ocal h os t vijai]$ ls -l list.sh-rwxrwxr-- 1 vijai vijai 30 Apr 4 13:58 list.sh

[v i jai@ l ocal h os t vijai]$ chmod 740 list.sh[v i jai@ l ocal h os t vijai]$ ls -l list.sh-rwxr----- 1 vijai vijai 30 Apr 4 13:58 list.sh

Page 14: Ge 2155 Full

Unix Commands GE2155–Computer Practice II

Ex. No: 1.3 STUDY OF VI EDITOR

Aim

To introduce the concept of text editing vi editor and the options regarding the controlof 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 Joy. "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 mode—Where any key depressed is entered as text2. Command mode—Where keys are used as commands to act on text (initial mode)3. ex mode—ex mode commands that can be entered in the last line to act on text

INPUT MODE

vi modes

vi starts with command mode. To insert text any of the following commands should be used.

Commands Functioni Inserts text to the left of the cursor.I Inserts text at the beginning of line.a Appends text to right of cursorA Appends text at end of lineo Opens line belowO Opens line above

In Input mode the editor displays INSERT in the last line. Press Enter key to start a fresh line of text in Input mode and the ~ disappears. To quit input mode press Esc key.

Page 15: Ge 2155 Full

Unix Commands GE2155–Computer Practice II

COMMAND MODE

EDIT COMMANDS

Command FunctionR 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 to Input mode.x Deletes the character in the current cursor position?text Locates the text in the file. If not found, the message "Pattern not found"

appears. Use n to repeat the forward search and N for backward search.U or u Reverses the last change made to the buffer.dd Cuts the entire linedw Cuts the entire wordd$ Cuts a line from cursor position to the end of the lined0 Cuts from the cursor position to the start of the lineyy Copies (yanks) the entire lineyw Copies the entire wordp Pastes the text

NAVIGATION COMMANDS

Command Functionb Moves back to beginning of a wordw Moves forward to beginning of word| Moves to start of the line$ Moves to end of the linek Up one linej Down one lineh Left one characterl Right one characterCtrl+f Scrolls a page forwardCtrl+b Scrolls a page backwardlG 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 example 3x 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 press Enter key to execute the same.

Page 16: Ge 2155 Full

vi editor

Unix Commands GE2155–Computer Practice II

Command Functionw 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 nameL1,L2 w file 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 savewq Save and exitsh 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 use gc instead of g.

r file To insert another file into the current file.new file Splits screen into multiple windows and opens the file.

This is vi improved – vimA rudimentary text~~~~~~~~~“Sample.txt” 2L, 30C written

vi Editor

ResultThus the study of text manipulation using vi editor has been completed successfully.

Page 17: Ge 2155 Full

Unix Commands GE2155–Computer Practice II

Ex. No: 1.4 Simple Filters

AimTo 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 Functionheadʊused to display the first few records (10 records by default)head stud Displays first 10 records by defaulthead -5 stud Displays first 5 recordshead -1 stud | wc –c length of first recordtailʊused to display the last few records (10 records by default)tail stud Displays last 10 records by defaulttail -5 stud | tee last5 Last 5 records listed & stored in file last5 using teecutʊused to extract specific fields. The d option specifies the delimiter and f for specifying the field list. The c option may be used if extraction is done character wisecut –d \| -f 1,3,4 stud Fields 1,3,4 listedcut –d \| -f 2-4 stud Fields 2,3,4 listedpaste –d \| list1 list2 merges two cut files list1 and list2sortʊreorders the file as per ASCII sequence. The t option is used to specify delimiter andk option to specify the fieldsort stud Sorted on 1st column by defaultsort –t \| -k 3 stud Sort as per 3rd columnsort –c stud Check if file is sorted using c optionsort -t \| -k 4,4 -k 3,3 stud

Sorting on secondary keys

sort -t \| -nr –k 4 stud Sort on numeric field using n option, r for reverseuniq stud Display unique entries in a sorted filetrʊtranslates characters. Can be used to change text case. It works with standard input <tr '[a-z]' '[A-Z]' < stud Changes text to upper casenlʊdisplay file content with lines numbered. The s option is used to specify separatornl –s "|" stud Displays entries numbered with separator |

Result

Thus information retrieval using filters has been completed successfully.

Page 18: Ge 2155 Full

Unix Commands GE2155–Computer Practice II

20057801|Aarthi |ECE |CTS |3600020057702|Albert Jerry |CSE |Wipro |2500020057903|Arun |IT |Ramco |1200020057904|Diwakar |IT |TCS |1050020057705|Geetha |CSE |Infosys |2300020057806|Irudayaraj |ECE |Polaris |3000020057707|Jaya Prakash |CSE |Ramco |2800020058008|Mahesh |EEE |Microsoft |500020057909|Manimaran |IT |Microsoft |900020058010|Mohammed Mukthar20057711|Prithivi Rajan

|EEE|CSE

|Oracle|Ramco

|6000|25000

20057712|Pushpak Chander |CSE |CTS |2750020057713|Ramesh |CSE |Wipro |2400020057817|Smitha |ECE |Ramco |3000020057718|Sri Gurumoorthy20057719|Tamil Selvi

|IT|EEE

|Microsoft|CTS

|11000|3500

20057720|Thamotharan |IT |CTS |9000

stud file

[vi jai@l ocalh ost filters]$ head stud20057801|Aarthi20057702|Albert Jerry20057903|Arun

|ECE|CSE|IT

|CTS|Wipro|Ramco

|36000|25000|12000

20057904|Diwakar20057705|Geetha20057806|Irudayaraj20057707|Jaya Prakash20058008|Mahesh20057909|Manimaran20058010|Mohammed Mukthar

|IT|CSE|ECE|CSE|EEE|IT|EEE

|TCS|Infosys|Polaris|Ramco|Microsoft|Microsoft|Oracle

|10500|23000|30000|28000|5000|9000|6000

[vi jai@l ocalh ost filters]$ head -4 stud20057801|Aarthi |ECE |CTS |3600020057702|Albert20057903|Arun20057904|Diwakar

Jerry |CSE|IT|IT

|Wipro|Ramco|TCS

|25000|12000|10500

[v i jai@ l ocal h os t filters]$ head -1 stud | wc -c49

[vi jai@l ocalh ost filters]$ tail stud20058008|Mahesh20057909|Manimaran

|EEE|IT

|Microsoft|Microsoft

|5000|9000

20058010|Mohammed Mukthar20057711|Prithivi Rajan

|EEE|CSE

|Oracle|Ramco

|6000|25000

20057712|Pushpak Chander20057713|Ramesh20057817|Smitha20057718|Sri Gurumoorthy

|CSE|CSE|ECE|IT

|CTS|Wipro|Ramco|Microsoft

|27500|24000|30000|11000

Page 19: Ge 2155 Full

Unix Commands GE2155–Computer Practice II

20057719|Tamil Selvi |EEE |CTS |350020057720|Thamotharan |IT |CTS |9000

[vi jai@l ocalh ost filters]$ tail -2 stud | tee last220057719|Tamil Selvi20057720|Thamotharan

|EEE|IT

|CTS|CTS

|3500|9000

[v i jai@ l ocal h os t filters]$ cat last220057719|Tamil Selvi20057720|Thamotharan

|EEE|IT

|CTS|CTS

|3500|9000

[v i jai@ l ocal h os t filters]$ cut -d \| -f 2,4-5 stud20057801|Aarthi |ECE20057702|Albert Jerry |CSE20057903|Arun |IT20057904|Diwakar |IT20057705|Geetha |CSE20057806|Irudayaraj |ECE20057707|Jaya Prakash |CSE20058008|Mahesh |EEE20057909|Manimaran |IT20058010|Mohammed Mukthar |EEE20057711|Prithivi Rajan |CSE20057712|Pushpak Chander |CSE20057713|Ramesh |CSE20057817|Smitha |ECE20057718|Sri Gurumoorthy |IT20057719|Tamil Selvi |EEE20057720|Thamotharan |IT

[v i jai@ l ocal h os t filters]$ cut -d \| -f 2,4 stud > nameorg [v i jai@ l ocal h os t filters]$ cut -d \| -f 5 stud > sal [v i jai@ l ocal h os t filters]$ paste -d \| nameorg salAarthi |CTS |36000Albert Jerry |Wipro |25000Arun |Ramco |12000Diwakar |TCS |10500Geetha |Infosys |23000Irudayaraj |Polaris |30000Jaya Prakash |Ramco |28000Mahesh |Microsoft |5000Manimaran |Microsoft |9000Mohammed Mukthar |Oracle |6000Prithivi Rajan |Ramco |25000Pushpak Chander |CTS |27500Ramesh |Wipro |24000Smitha |Ramco |30000Sri Gurumoorthy |Microsoft |11000Tamil Selvi |CTS |3500Thamotharan |CTS |9000

Page 20: Ge 2155 Full

Unix Commands GE2155–Computer Practice II

[vi jai@l ocalh ost filters]$ sort stud20057702|Albert Jerry20057705|Geetha20057707|Jaya Prakash20057711|Prithivi Rajan20057712|Pushpak Chander20057713|Ramesh

|CSE|CSE|CSE|CSE|CSE|CSE

|Wipro|Infosys|Ramco|Ramco|CTS|Wipro

|25000|23000|28000|25000|27500|24000

20057718|Sri Gurumoorthy20057719|Tamil Selvi20057720|Thamotharan20057801|Aarthi20057806|Irudayaraj20057817|Smitha20057903|Arun

|IT|EEE|IT|ECE|ECE|ECE|IT

|Microsoft|CTS|CTS|CTS|Polaris|Ramco|Ramco

|11000|3500|9000|36000|30000|30000|12000

20057904|Diwakar20057909|Manimaran

|IT|IT

|TCS|Microsoft

|10500|9000

20058008|Mahesh20058010|Mohammed Mukthar

|EEE|EEE

|Microsoft|Oracle

|5000|6000

[vi jai@l ocalh ost filters]$ sort -t \| -k 1 stud20057801|Aarthi20057702|Albert Jerry

|ECE|CSE

|CTS|Wipro

|36000|25000

20057903|Arun20057904|Diwakar20057705|Geetha

|IT|IT|CSE

|Ramco|TCS|Infosys

|12000|10500|23000

20057806|Irudayaraj20057707|Jaya Prakash

|ECE|CSE

|Polaris|Ramco

|30000|28000

20058008|Mahesh20057909|Manimaran

|EEE|IT

|Microsoft|Microsoft

|5000|9000

20058010|Mohammed Mukthar20057711|Prithivi Rajan20057712|Pushpak Chander

|EEE|CSE|CSE

|Oracle|Ramco|CTS

|6000|25000|27500

20057713|Ramesh20057817|Smitha

|CSE|ECE

|Wipro|Ramco

|24000|30000

20057718|Sri Gurumoorthy20057719|Tamil Selvi20057720|Thamotharan

|IT|EEE|IT

|Microsoft|CTS|CTS

|11000|3500|9000

[vi jai@l ocalh ost filters]$ sort -t \| -k 4,4 -k 3,3 stud20057712|Pushpak Chander20057801|Aarthi20057719|Tamil Selvi

|CSE|ECE|EEE

|CTS|CTS|CTS

|27500|36000|3500

20057720|Thamotharan20057705|Geetha20058008|Mahesh20057718|Sri Gurumoorthy20057909|Manimaran20058010|Mohammed Mukthar

|IT|CSE|EEE|IT|IT|EEE

|CTS|Infosys|Microsoft|Microsoft|Microsoft|Oracle

|9000|23000|5000|11000|9000|6000

Page 21: Ge 2155 Full

Unix Commands GE2155–Computer Practice II

20057806|Irudayaraj20057711|Prithivi Rajan20057707|Jaya Prakash20057817|Smitha20057903|Arun

|ECE|CSE|CSE|ECE|IT

|Polaris|Ramco|Ramco|Ramco|Ramco

|30000|25000|28000|30000|12000

20057904|Diwakar20057713|Ramesh

|IT|CSE

|TCS|Wipro

|10500|24000

20057702|Albert Jerry |CSE |Wipro |25000

[vi jai@l ocalh ost filters]$ sort -t \| -nr -k 5 stud20057801|Aarthi20057817|Smitha20057806|Irudayaraj20057707|Jaya Prakash20057712|Pushpak Chander

|ECE|ECE|ECE|CSE|CSE

|CTS|Ramco|Polaris|Ramco|CTS

|36000|30000|30000|28000|27500

20057711|Prithivi Rajan20057702|Albert Jerry

|CSE|CSE

|Ramco|Wipro

|25000|25000

20057713|Ramesh20057705|Geetha20057903|Arun20057718|Sri Gurumoorthy20057904|Diwakar

|CSE|CSE|IT|IT|IT

|Wipro|Infosys|Ramco|Microsoft|TCS

|24000|23000|12000|11000|10500

20057909|Manimaran20057720|Thamotharan20058010|Mohammed Mukthar

|IT|IT|EEE

|Microsoft|CTS|Oracle

|9000|9000|6000

20058008|Mahesh20057719|Tamil Selvi

|EEE|EEE

|Microsoft|CTS

|5000|3500

[vi jai@l ocalh ost filters]$ tr '[a-z]' '[A-Z]' < stud20057801|AARTHI20057702|ALBERT JERRY

|ECE|CSE

|CTS|WIPRO

|36000|25000

20057903|ARUN20057904|DIWAKAR

|IT|IT

|RAMCO|TCS

|12000|10500

20057705|GEETHA |CSE |INFOSYS |2300020057806|IRUDAYARAJ |ECE |POLARIS |3000020057707|JAYA PRAKASH20058008|MAHESH20057909|MANIMARAN20058010|MOHAMMED MUKTHAR20057711|PRITHIVI RAJAN

|CSE|EEE|IT|EEE|CSE

|RAMCO|MICROSOFT|MICROSOFT|ORACLE|RAMCO

|28000|5000|9000|6000|25000

20057712|PUSHPAK CHANDER20057713|RAMESH

|CSE|CSE

|CTS|WIPRO

|27500|24000

20057817|SMITHA20057718|SRI GURUMOORTHY20057719|TAMIL SELVI

|ECE|IT|EEE

|RAMCO|MICROSOFT|CTS

|30000|11000|3500

20057720|THAMOTHARAN |IT |CTS |9000

Page 22: Ge 2155 Full

Unix Commands GE2155–Computer Practice II

Ex. No: 1.5 Regular Expression

AimTo 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 and egrep enables searching for multiple patterns. Its usage is

grep options searchtext filename

Command Functiongrep this demo Lists the lines that contains the string thisgrep 'end of' demo Quotes mandatory for text containing spacegrep this demo* Search this in multiple filesgrep –c to demo Number of occurrence of the word to in the filegrep –n sequence demo Display line numbers along with matching linesgrep –v word demo Displays lines that does not contain the text wordgrep –l vim * Displays files containing text vimgrep –i WORD demo Search for text ignoring case differencesgrep '^[0-9]' demo Lines that start with a numbergrep '[0-9]$' demo Lines that end with a numberls -l | grep "^d" Display the subdirectory namesgrep –c "^$" demo Display count of blank lines in the file.grep "2....$" stud Display lines that ends in the range 20000–29999egrep "lower|UPPER" demo Display lines that match either lower or upperegrep "(previous|current)word" demo

Display lines that match either previous word orcurrent word

Result

Thus searching text patterns in files using grep has been completed successfully.

Page 23: Ge 2155 Full

Unix Commands GE2155–Computer Practice II

THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE. this line is the 1st lower case line in this file.This Line Has All Its First Character Of The Word With Upper Case.

Two lines above this line is empty. vim Word Navigation

You may want to do several navigation in relation to words, such as:

1. e - go to the end of the current word.2. E - go to the end of the current WORD.3. b - go to the previous word.4. B - go to the previous WORD.

WORD - WORD consists of a sequence of non-blank charactersWord - word consists of a sequence of letters, digits and underscores.

telnet 172.16.4.256

demo file

[v i jai@ l ocal h os t regexpr]$ grep this demothis line is the 1st lower case line in this file. Two lines above this line is empty.

[v i jai@ l ocal h os t regexpr]$ grep 'end of' demo1. e - go to the end of the current word.2. E - go to the end of the current WORD.

[v i jai@ l ocal h os t regexpr]$ grep -c to demo5

[v i jai@ l ocal h os t regexpr]$ grep -n sequence demo15:WORD - WORD consists of a sequence of non-blank characters16:Word - word consists of a sequence of letters, digits and underscores.

[v i jai@ l ocal h os t regexpr]$ grep -v word demo THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE. this line is the 1st lower case line in this file.This Line Has All Its First Character Of The Word With Upper Case.

Two lines above this line is empty. vim Word Navigation

2. E - go to the end of the current WORD.4. B - go to the previous WORD.

WORD - WORD consists of a sequence of non-blank characters

telnet 172.16.4.256

Page 24: Ge 2155 Full

Unix Commands GE2155–Computer Practice II

[v i jai@ l ocal h os t regexpr]$ grep -l vim *demo readme

[v i jai@ l ocal h os t regexpr]$ grep -i WORD demoThis Line Has All Its First Character Of The Word With Upper Case. vim Word NavigationYou may want to do several navigation in relation to words, such as:1. e - go to the end of the current word.2. E - go to the end of the current WORD.3. b - go to the previous word.4. B - go to the previous WORD.WORD - WORD consists of a sequence of non-blank charactersWord - word consists of a sequence of letters, digits and underscores.

[v i jai@ l ocal h os t regexpr]$ grep '^[0-9]' demo1. e - go to the end of the current word.2. E - go to the end of the current WORD.3. b - go to the previous word.4. B - go to the previous WORD.

[v i jai@ l ocal h os t regexpr]$ grep '[0-9]$' demotelnet 172.16.4.256

[vi jai@l ocalh ost vijai]$ ls -l | grep "^d"drwxrwxr-x 2 vijai vijai 4096 Apr 9 14:30 regexprdrwxrwxr-x 7 vijai vijai 4096 Apr 4 14:57 shellscripts

[v i jai@ l ocal h os t regexpr]$ grep -c "^$" demo5

[v i jai@ l ocal h os t regexpr]$ egrep "lower|UPPER" demoTHIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE. this line is the 1st lower case line in this file.

[ v i jai@l o c a lho s t regexpr]$ egrep "(previous|current) word" demo1. e - go to the end of the current word.3. b - go to the previous word.

Page 25: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

Ex. No: 2.1 SIMPLE PROGRAMS

AimTo 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.

Preliminaries1. 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. The read statement is shell's internal tool for making scripts interactive.

4. Output is displayed using echo statement. Any text should be within quotes. Escape sequence should be used with –e 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 the sh command (sh filename).

ResultThus using programming basics, simple shell scripts were executed

Page 26: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

2.1.A—Swapping values of two variables

Algorithm

Step 1 : StartStep 2 : Read the values of a and bStep 3 : Interchange the values of a and b using another variable t as follows:

t = a a = b b = t

Step 4 : Print a and bStep 5 : Stop

Program (swap.sh)

# Swapping valuesecho -n "Enter value for A : " read aecho -n "Enter value for B : "read b t=$a a=$b b=$techo "Values after Swapping"echo "A Value is $a" echo "B Value is $b"

Output

[v i jai@ l ocal h os t simple]$ sh swap.shEnter value for A : 12Enter value for B : 23Values after SwappingA Value is 23B Value is 12

2.1.B—Farenheit to Centigrade Conversion

Algorithm

Step 1 : StartStep 2 : Read fahrenheit valueStep 3 : Convert fahrenheit to centigrade using the formulae: (fahrenheit – 32) × 5/9Step 4 : Print centigradeStep 5 : Stop

Page 27: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

Program (degconv.sh)

# Degree conversionecho -n "Enter Fahrenheit : " read fc=`expr \( $f - 32 \) \* 5 / 9`echo "Centigrade is : $c"

Output

[v i jai@ l ocal h os t simple]$ sh degconv.shEnter Fahrenheit : 213Centigrade is : 100

2.1.C— Area & Circumference of Circle

Algorithm

Step 1 : StartStep 2 : Define constant pi = 3.14Step 3 : Read the value of radiusStep 4 : Calculate area using formulae: pi × radius2

Step 5 : Calculate circumference using formulae: 2 × pi × radiusStep 6 : Print area and circumferenceStep 7 : Stop

Program (circle.sh)

# Circle metrics using readonly variable pi=`expr "scale=2; 22 / 7" | bc`readonly pi # pi value cannot be alteredecho -n "Enter value for radius : " read radiusarea=`expr "scale=2; $pi * $radius * $radius" | bc`circum=`expr "scale=2; 2 * $pi * $radius" | bc`echo "Area : $area"echo "Circumference : $circum"

Output

[v i jai@ l ocal h os t simple]$ sh circle.shEnter value for radius : 12Area : 452.16Circumference : 75.36

Page 28: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

2.1.D— Simple Interest Calculation

Algorithm

Step 1 : StartStep 2 : Read the values principal, rate and yearsStep 3 : Compute simpleinterest using the formulae: (principal × rate × years) / 100Step 4 : Print simpleinterestStep 5 : Stop

Program (simpint.sh)

# Interest computation using bcecho -n "Enter Principal amount : " read pecho -n "Enter number of years : " read necho -n "Enter rate of interest : " read rsi=`expr "scale=2; $p * $n *$r / 100" | bc`echo "Simple Interest : $si"

Output

[v i jai@ l ocal h os t simple]$ sh simpint.shEnter Principal amount : 1285Enter number of years : 3Enter rate of interest : 5Simple Interest : 192.75

Page 29: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

Ex. No: 2.2 CONDITIONAL STATEMENT

AimTo write shell programs using decision-making constructs.

Shell supports decision-making using if statement. The if 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.

if [ condition ]then

statementsfi

if [ condition ]then

statementselse

statementsfi

if [condition ]then

statementselif [ condition ]then

statements.. .else

statementsfi

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-lt Less than-le Less than or equal to-a Logical AND-o Logical OR! Logical NOT

ResultThus using if statement scripts with conditional expressions were executed

Page 30: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

2.2.A— Odd or even

Algorithm

Step 1 : StartStep 2 : Read numberStep 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 using if-elseecho -n "Enter a non-zero number : " read numrem=`expr $num % 2` if [ $rem -eq 0 ] then

echo "$num is Even" else

echo "$num is Odd"fi

Output

[v i jai@ l ocal h os t decision]$ sh oddeven.shEnter a non-zero number : 1212 is Even

2.2.B—Biggest of 3 numbers

Algorithm

Step 1 : StartStep 2 : Read values of a, b and cStep 3 : If a > b and a > 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

Page 31: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

Program (big3.sh)

# Biggest using logical expression echo -n "Give value for A B and C: " read a b cif [ $a -gt $b -a $a -gt $c ]then

echo "A is the Biggest number" elif [ $b -gt $c ]then

echo "B is the Biggest number" else

echo "C is the Biggest number"fi

Output

[v i jai@ l ocal h os t decision]$ sh big3.shGive value for A B and C: 4 3 4C is the Biggest number

2.2.C—Leap year

Algorithm

Step 1 : StartStep 2 : Read the value of yearStep 3 : If year divisible by 400 then

Print "Leap year"Step 3.1 : else if year divisible by 4 and not divisible by 100 then

Print "Leap year"Step 3.2 : else

Print "Not a leap year"Step 4 : Stop

Program (leap.sh)

# Leap yearecho -n "Enter a year : " read yearrem1=`expr $year % 4` rem2=`expr $year % 100` rem3=`expr $year % 400` if [ $rem3 -eq 0 ]then

echo "$year is a Leap Year"elif [ $rem2 -ne 0 -a $rem1 -eq 0 ]then

echo "$year is a Leap Year" else

echo "$year is Not a leap year"fi

Page 32: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

Output

[v i jai@ l ocal h os t decision]$ sh leap.shEnter a year : 19001900 is Not a leap year

2.2.D—Grade Determination

Algorithm

Step 1 : StartStep 2 : Read markStep 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 t 50 then

Print "E grade" Step 3.6 : else

Print "U grade"Step 4 : Stop

Program (grade.sh)

echo -n "Enter the mark : " read markif [ $mark -gt 90 ]then

echo "S Grade"elif [ $mark -gt 80 ]then

echo "A Grade"elif [ $mark -gt 70 ]then

echo "B Grade"elif [ $mark -gt 60 ]then

echo "C Grade"elif [ $mark -gt 55 ]then

echo "D Grade"

Page 33: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

elif [ $mark -ge 50 ]then

echo "E Grade" else

echo "U Grade"fi

Output

[v i jai@ l ocal h os t decision]$ sh grade.shEnter the mark : 65C Grade

2.2.E—String comparison

Algorithm

Step 1 : StartStep 2 : Read strings str1 and str2Step 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 "Enter the first string : " read s1echo -n "Enter the second string : "read s2if [ $s1 == $s2 ]thenecho "Strings are the same" elseecho "Strings are distinct" fi

Output

[v i jai@ l ocal h os t decision]$ sh strcomp.shEnter the first string : ece-a Enter the second string : ECE-A Strings are distinct

Page 34: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

2.2.F—Employee Pay Calculation

Algorithm

Step 1 : StartStep 2 : Read basicStep 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 thenhra is 4% of basic da is 3% of basic tax is 8% of basic

Step 3.2 : elsehra is 3% of basic da is 2% of basic tax is 5% of basic

Step 4 : Stop

Program (emppay.sh)

echo -n "Enter employee basic pay : " read basicif [ $basic -gt 30000 ]then

hra=`expr 5 \* $basic / 100` da=`expr 5 \* $basic / 100` tax=`expr 10 \* $basic / 100`

elif [ $basic -gt 20000 ]then

else

fi

hra=`expr 4 \* $basic / 100` da=`expr 3 \* $basic / 100` tax=`expr 8 \* $basic / 100`

hra=`expr 3 \* $basic / 100` da=`expr 2 \* $basic / 100` tax=`expr 5 \* $basic / 100`

gross=`expr $basic + $da + $hra`netpay=`expr $gross - $tax` echo "Gross Pay : $gross" echo "Net Pay : $netpay"

Output

[v i jai@ l ocal h os t decision]$ sh emppay.shEnter employee basic pay : 12000Gross Pay : 12600Net Pay : 12000

Page 35: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

Ex. No: 2.3 MULTI-WAY BRANCHING

AimTo write shell programs using case construct to match patterns.

The case 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 inconstant1)

statements ;;constant2)

statements ;;. . .

constantN)statements ;;*)statements

esac

ResultThus using case statement, shell scripts were executed

Page 36: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

2.3.A—Vowel or Consonant

Algorithm

Step 1 : StartStep 2 : Read charStep 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 with multiple values in a pattern echo -n "Key in a lower case character : " read choicecase $choice in

a|e|i|o|u) echo "It's a Vowel";;*) echo "It's a Consonant"

esac

Output

[v i jai@ l ocal h os t multway]$ sh vowel.cKey in a lower case character : eIt's a Vowel

2.3.B—Simple Calculator

Algorithm

Step 1 : StartStep 2 : Read operands a and b Step 3 : Display operation menu Step 4 : Read optionStep 5 : If option = 1 then

Calculate c = a + b Step 5.1 : else if option = 2 then

Calculate c = a – bStep 5.2 : else if option = 3 then

Calculate c = a * b Step 5.3 : else if option = 4 then

Calculate c = a / bStep 5.4 : else if option = 5 then

Calculate c = a % bStep 5.5 : else

Print "Invalid option" Step 6 : Print cStep 7 : Stop

Page 37: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

Program (calc.sh)

# Arithmetic operations--multiple statements in a block echo -n "Enter the two numbers : "read a becho " 1. Addition" echo " 2. Subtraction" echo " 3. Multiplication" echo " 4. Division"echo " 5. Modulo Division" echo -n "Enter the option : " read optioncase $option in

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 "Invalid Option" esac

Output

[v i jai@ l ocal h os t multway]$ sh calc.shEnter the two numbers : 2 41. Addition2. Subtraction3. Multiplication4. Division5. Modulo Division

Enter the option : 12 + 4 = 6

2.3.C—Rental Options

Algorithm

Step 1 : StartStep 2 : Read vehicleStep 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"

Page 38: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

Step 3.4 : elsePrint "Vehicle not available"

Step 4 : Stop

Program (rental.sh)

# String matchingecho "Two/Four wheeler rental"echo -n "Enter the required vehicle : " read vehiclecase $vehicle in

"car") echo "For $vehicle Rs.20 per km";; "van") echo "For $vehicle Rs.10 per km";;

"jeep") echo "For $vehicle Rs.5 per km";; "bicycle") echo "For $vehicle 20 paisa per km";;

*) echo "Sorry, I cannot get a $vehicle for you";;esac

Output

[v i jai@ l ocal h os t multway]$ sh rental.shTwo/Four wheeler rentalEnter the required vehicle : bicycleFor bicycle 20 paisa per km

2.3.D—Vote Eligibility (vote.sh)

Algorithm

Step 1 : StartStep 2 : Read ageStep 3 : If age ” 17

Print "Not eligible to vote" Step 3.1 : else

Print "Eligible to vote"Step 4 : Stop

Program

# Vote--range matchingecho -n "Enter your age : " read agecase $age in

[0-9]|1[0-7])echo "You are not eligible to vote";;*)echo "Eligible to vote"

esac

Output

[v i jai@ l ocal h os t multway]$ sh vote.shEnter your age : 12You are not eligible to vote

Page 39: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

Ex. No: 2.4 LOOPS

AimTo write shell programs using different types of loops.

Shell supports a set of loops such as for, while and until to execute a set of statements repeatedly. The body of the loop is contained between do and done statement.

The for loop doesn't test a condition, but uses a list instead.

for variable in listdo

donestatements

The while loop executes the statements as long as the condition remains true.

while [ condition ]do

donestatements

The until loop complements the while construct in the sense that the statements are executed as long as the condition remains false.

until [ condition ]do

done

Result

statements

Thus using loops, iterative scripts were executed

Page 40: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

2.4.A—Multiplication Table

Algorithm

Step 1 : StartStep 2 : Read the value of nStep 3 : Initialize 1 to i Step 4 : Print n, i, n×i Step 5 : Increment i by 1Step 6 : Repeat steps 4 and 5 until i d 10Step 7 : Stop

Program (multable.sh)

# Multiplication table using for loop clearecho -n "Which multiplication table? : "read nfor x in 1 2 3 4 5 6 7 8 9 10 do

p=`expr $x \* $n`echo -n "$n X $x = $p" sleep 1

done

Output

[v i jai@ l ocal h os t loops]$ sh multable.shWhich multiplication table? : 66 X 1 = 66 X 2 = 126 X 3 = 186 X 4 = 246 X 5 = 306 X 6 = 366 X 7 = 426 X 8 = 486 X 9 = 546 X 10= 60

2.4.B—Armstrong Number

Algorithm

Step 1 : StartStep 2 : Read numberStep 3 : Initialize 0 to sum and number to numStep 4 : Extract lastdigit by computing number modulo 10Step 5 : Cube the lastdigit and add it to sumStep 6 : Divide number by 10Step 7: Repeat steps 4–6 until number > 0

Page 41: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

Step 8 : If sum = number thenPrint “Armstrong number”

Step 8.1 : elsePrint “Not an Armstrong number”

Step 9 : Stop

Program (armstrong.sh)

# Armstrong number using while loop echo -n "Enter a number : "read n a=$n s=0while [ $n -gt 0 ]do

r=`expr $n % 10`s=`expr $s + \( $r \* $r \* $r \)`n=`expr $n / 10`

doneif [ $a -eq $s ]then

echo "Armstrong Number" else

echo -n "Not an Armstrong number"fi

Output

[v i jai@ l ocal h os t loops]$ sh armstrong.shEnter a number : 370Armstrong Number

2.4.C—Number Reverse

Algorithm

Step 1 : StartStep 2 : Read numberStep 3 : Initialize 0 to reverseStep 4 : Extract lastdigit by computing number modulo 10Step 5 : Compute reverse = reverse10 + lastdigitStep 6 : Divide number by 10Step 7: Repeat steps 4–6 until number > 0Step 8 : Print reverseStep 9 : Stop

Page 42: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

Program (reverse.sh)

# To reverse a number using while loop echo -n "Enter a number : "read n rd=0while [ $n -gt 0 ]do

rem=`expr $n % 10`rd=`expr $rd \* 10 + $rem`n=`expr $n / 10`

doneecho "Reversed number is $rd"

Output

[v i jai@ l ocal h os t loops]$ sh reverse.shEnter a number : 234Reversed number is 432

2.4.D—Fibonacci Series

Algorithm

Step 1 : StartStep 2 : Read number of terms as nStep 3 : Initialize 0 to f1, 1 to f2 and 2 to iStep 4 : Print initial fibonacci terms f1, f2Step 5 : Generate next term using the formula f3 = f1 + f2Step 6 : Print f3Step 7 : Increment i by 1Step 8 : Assign f2 to f1Step 9 : Assign f3 to f2Step 10 : Repeat steps 5–9 until i d nStep 11 : Stop

Program (fibo.sh)

# Fibonacci series using while loop echo -n "Enter number of terms : " read necho "Fibonacci Series" f1=0f2=1echo -n "$f1 " echo -n " $f2 " i=2

Page 43: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

while [ $i -lt $n ]do

f3=`expr $f1 + $f2` echo -n " $f3 " f1=$f2f2=$f3i=`expr $i + 1`

done echo

Output

[v i jai@ l ocal h os t loops]$ sh fibo.shEnter number of terms : 8Fibonacci Series0 1 1 2 3 5 8 13

2.4.E—Prime Number

Algorithm

Step 1 : StartStep 2 : Read the value of nStep 3 : Initialize i to 2Step 4 : If n is divisible by i then

Print “Not Prime” and StopStep 5 : Increment i by 1Step 6 : Repeat steps 4 and 5 until i d n/2Step 7 : Print "Prime" Step 8 : Stop

Program (prime.sh)

# Prime number using exitecho -n "Enter the number : " read ni=2m=`expr $n / 2` until [ $i -gt $m ] do

q=`expr $n % $i`if [ $q -eq 0 ]then

echo "Not a Prime number" exit

fii=`expr $i + 1`

doneecho "Prime number"

Page 44: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

Output

[v i jai@ l ocal h os t loops]$ sh prime.shEnter the number : 17Prime number

2.4.F—Factorial Value

Algorithm

Step 1 : StartStep 2 : Read numberStep 3 : Initialize 1 to fact and number to iStep 4 : fact = fact * iStep 5 : Decrement i by 1Step 6: Repeat steps 4–6 until i > 0Step 7 : Print factStep 8 : Stop

Program (fact.sh)

# Factorial value using untilecho -n "Enter a positive number : " read nf=1until [ $n -lt 1 ]do

f=`expr $f \* $n`n=`expr $n - 1`

doneecho "Factorial value : $f"

Output

[v i jai@ l ocal h os t loops]$ sh fact.shEnter a positive number : 10Factorial value : 3628800

2.4.G—Sum of 1..N natural numbers

Algorithm

Step 1 : StartStep 2 : Read nStep 3 : Initialize 0 to sum and 1 to iStep 4 : Add i to sumStep 5 : Increment i by 1Step 6: Repeat steps 4–6 until i ” nStep 7 : Print sumStep 8 : Stop

Page 45: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

Program (sum1ton.sh)

# Sum of 1+2+3+ ... +N numbers echo -n "Enter N value : "read n sum=0 i=1until [ $i -gt $n ]do

sum=`expr $sum + $i`i=`expr $i + 1`

doneecho "The sum of n numbers is $sum"

Output

[v i jai@ l ocal h os t loops]$ sh sum1ton.shEnter N value : 26The sum of n numbers is 351

2.4.H—Data Statistics

Algorithm

Step 1 : StartStep 2 : Initialize 0 to pc, sum, iStep 3 : Read a numberStep 4 : If number = 9999 then goto step 10Step 5 : Increment i by 1Step 6 : If number ” 0 then goto step 3Step 7 : Increment pc by 1Step 8 : Add number to sumStep 9 : Goto step 3Step 10 : Compute avg = sum / pcStep 11 : Print i, pc, avg, Step 12 : Stop

Program (datastat.sh)

# Aggregate of positive nos using break and continue clearpc=0 s=0 i=0

Page 46: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

until false do

echo -n "Enter a number (9999 to quit) : " read nif [ $n -eq 9999 ]then

breakfii=`expr $i + 1` if [ $n -le 0 ] then

continuefipc=`expr $pc + 1`s=`expr $s + $n`

doneavg=`expr "scale=2; $s / $pc" | bc`echo "Total No. of entries : $i" echo "No. of positive datas : $pc" echo "Positive aggregate : $avg"

Output

[v i jai@ l ocal h os t loops]$ sh datastat.shEnter a number (9999 to quit) : 32Enter a number (9999 to quit) : 78Enter a number (9999 to quit) : 0Enter a number (9999 to quit) : 11Enter a number (9999 to quit) : 47Enter a number (9999 to quit) : -9Enter a number (9999 to quit) : 12Enter a number (9999 to quit) : 7Enter a number (9999 to quit) : 9999Total No. of entries : 8No. of positive datas : 6Positive aggregate : 31.16

Page 47: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

Ex. No: 2.5 SHELL SCRIPTS

AimTo 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

#!/bin/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-w filename 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-emptyfile1 -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

ResultThus programming constructs using shell commands were executed

Page 48: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

2.5.A—Time based greeting

Program (wish.sh)

#!/bin/bash x=`date +%H` mrd=`date +%P`if [ $mrd=='am' ]then

if [ $x -le 11 ]then

echo "Good Morning"fi

elseif [ $x -le 2 ]then

echo "Good Afternoon" elif [ $x -le 6 ]then

echo "Good Evening" else

echo "Good Night"fi

fi

Output[vi jai@l ocalh ost command]$ sh wish.shGood Morning

2.5.B—Number of days in a month

Program (monthdays.sh)

# Number of days in a month mth=`date +%m`mn=`date +%B`case $mth in

02)echo "February usually has 28 days"echo "If leap year, then it has 29 days" ;;

04|06|09|11)echo "The current month $mn has 30 days" ;;*) echo "The current month $mn has 31 days"

esac

Output

[v i jai@ l ocal h os t command]$ sh monthdays.shThe current month April has 30 days

Page 49: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

2.5.C—Commands menu

Program (cmdmenu.sh)

# Menu program ch='y'while [ $ch == 'y' ]do

echo -e "\tMENU1. List of files2. Working Directory3. Date and Time4. Users of the system5. CalendarEnter the option : \c"

read choicecase "$choice" in

1) ls -l ;;2) pwd ;;3) date ;;4) who ;;5) cal

esacecho -n "Do you wish to continue (y/n) : " read ch

done

Output

[v i jai@ l ocal h os t command]$ sh cmdmenu.shMENU

1. List of files2. Working Directory3. Date and Time4. Users of the system5. CalendarEnter the option : 4

vijai pts/20 Apr 4 13:41 (linux-21.smkfomra.com)cse1 pts/13 Apr 4 13:43 (scl-58.smkfomra.com)Do you wish to continue (y/n) : n

2.5.D—Directory Listing

Program (cmdmenu.sh)

for x in . do

ls -R $x done

Page 50: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

Output

[v i jai@ l ocal h os t command]$ sh list.sh.:list.sh shellscripts

./shellscripts:command decision loops patmatch simple

./shellscripts/command:cmdmenu.sh debug.sh dupremove.sh filetype.sh keystroke.sh

./shellscripts/decision:big3.sh emppay.sh grade.sh leap.sh oddeven.sh strcomp.sh

./shellscripts/loops:armstrong.sh datastat.sh fact.sh fibo.sh multable.sh

./shellscripts/patmatch:calc.sh rental.sh vote.sh vowel.sh

./shellscripts/simple:circle.sh degconv.sh simpint.sh swap.sh

2.5.E—Detecting file type

Program (filetype.sh)

# File typeecho -n "Enter filename : " read fnameif [ -e $fname ]then

if [ -f $fname ]then

echo "Regular file" elif [ -d $fname ]then

echo "Directory" else

echo "Special file"fi

elseecho "File does not exist"

fi

Output

[v i jai@ l ocal h os t command]$ sh filetype.shEnter filename : samp.cRegular file

Page 51: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

2.5.F—Detecting user when logged on

Program (logdetect.sh)

#!/bin/bash#Detect the user at logon while truedo

if who|grep $1>/dev/null then

echo $1 is logged inexit

fi done

Output

[v i jai@ l ocal h os t command]$ sh logdetect.sh cse1cse1 is logged in

2.5.G—Duplicate file removal

Program (dupremove.sh)

# Duplicate file removal if cmp $1 $2then

echo "Files $1, $2 are identical" rm $2echo "$2 file deleted"

elseecho "Files $1, $2 are distinct"

fi

Output

[v i jai@ l ocal h os t command]$ sh dupremove.sh samp.c s.cFiles samp.c, s.c are identical s.c file deleted

Page 52: Ge 2155 Full

Shell Programming GE2155–Computer Practice II

2.5.H—Compilation and execution of a C program

Program (debug.sh)# Compile and execute while truedo

gcc -o $1.out $1.c case "$?" in

0)echo "Executing ..."./$1.out exit;;

*)sleep 5 vi $1.c

esac done

Output

[v i jai@ l ocal h os t command]$ sh debug.sh samp samp.c:4:10: warning: multi-line string literals are deprecatedsamp.c:4:10: missing terminating " charactersamp.c:4:10: possible start of unterminated string literal samp.c: In function `main':samp.c:4: parse error at end of inputExecuting ... Hello

2.5.I—Keystroke detection

Program (keystroke.sh)# Detect key strokeecho "Hit a key and then hit return." read Keypresscase "$Keypress" in

[[:lower:]] ) echo "Lowercase letter";; [[:upper:]] ) echo "Uppercase letter";; [0-9] ) echo "Digit";;* ) echo "Punctuation, whitespace, or other";;

esac

Output

[v i jai@ l ocal h os t command]$ sh keystroke.sh8Digit

Page 53: Ge 2155 Full

C Programming GE2155–Computer Practice II

Ex. No: 3.1 Introduction to Pointers

AimTo 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 10 3221216948

The address of a variable can be obtained using & operator known as reference 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.

int x, *iptr;

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.

ptr = &x; /* Assigning address X to pointer */

Value of the variable pointed to can be accessed by applying the dereference operator

printf("Value of the variable pointed to %d",*ptr);

A pointer of type void is referred to as generic 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 as pointer-to-pointer.

ResultThus C programs using pointers were executed.

Page 54: Ge 2155 Full

C Programming GE2155–Computer Practice II

3.1.A—Reference and Dereference operator

Algorithm

Step 1 : StartStep 2 : Initialize x to 10Step 3 : Print the value of xStep 4 : Print the address of x using address operatorStep 5 : Print the value of x by dereferencing the address operatorStep 6 : Stop

Program (refderef.c)

/* Data and address */#include <stdio.h>main(){

int x;x=10;printf("Value of x is %d",x); printf("\nAddress of x is %u",&x); printf("\nValue of x is %d\n",*(&x));

}

Output

[v i jai@ l ocal h os t pointer]$ gcc refderef.c[v i jai@ l ocal h os t pointer]$ ./a.outValue of x is 10Address of x is 3221216948Value of x is 10

3.1.B—Pointer variables

Algorithm

Step 1 : Initialize two integer variables x and y with some values. Step 2 : Create a pointer iptr of integer typeStep 3 : Assign the address of x to iptrStep 4 : Print the value and address stored in iptrStep 5 : Assign the address of y to iptrStep 6 : Print the value and address stored in iptrStep 7 : Print the storage requirement of iptr, address of iptr and main function

Page 55: Ge 2155 Full

C Programming GE2155–Computer Practice II

Program (ptrvar.c)

/* Pointer variables */# include<stdio.h>main(){

int x, y, *iptr;x = 125;iptr = &x ; /* iptr points to x */y = 23;float *fptr;

printf("X value is %d and stored at %u\n", x, &x);printf("Y value is %d and stored at %u\n", y, &y);

printf("\nInt pointer holds the address %u\n", iptr);printf("Aceesing value thru pointer : %d\n", *iptr);

iptr = &y; /* iptr points to y */printf("\nInt pointer now holds the address %u\n", iptr);printf("Accessing value thru pointer : %d\n", *iptr);

printf("\nSize of int pointer: %d bytes", sizeof(iptr)); printf("\nSize of float pointer: %d bytes", sizeof(fptr)); printf("\n\nAddress of main function is %u\n", main);

}

Output

[v i jai@ l ocal h os t pointer]$ gcc ptrvar.c[v i jai@ l ocal h os t pointer]$ ./a.outX value is 125 and stored at 3221216452Y value is 23 and stored at 3221216448

Int pointer holds the address 3221216452Aceesing value thro pointer : 125

Int pointer now holds the address 3221216448Accessing value thro pointer : 23

Size of int pointer: 4 bytesSize of float pointer: 4 bytes

Address of main function is 134513448

3.1.C—Pointer–to–Pointer

Algorithm

Step 1 : Demonstrate void pointer by making it to point to variables of different typeStep 2 : Declare a pointer variable p1 and assign a variable's address of its typeStep 3 : Declare a double pointer p2 and assign it the address of p1Step 4 : Display the address stored in p1, data accessed using p1 and p1's address Step 5 : Display the address stored in p2, data accessed using p2 and p2's address Step 6 : Stop

Page 56: Ge 2155 Full

C Programming GE2155–Computer Practice II

Program (ptrtoptr.c)

/* Pointer variables */# include<stdio.h>main(){

int x=12, *p1, **p2;float z=8.5;void *ptr; /* Generic pointer */ptr = &x ; /* ptr points to x (int) */ptr = &z; /* ptr points to y (float) */

p1 = &x;p2 = &p1; /* Pointer to pointer */printf("X value is %d and stored at %u\n", x, &x);

printf("\nPointer holds the address %u\n", p1); printf("Aceesing value thru pointer : %d\n", *p1); printf("Pointer is stored at location : %u\n",&p1);

printf("\nPointer-to-pointer holds the address %u\n", p2);printf("Accessing value thru ptr-to-ptr : %d\n", **p2);

printf("\nSize of ptr-to-ptr: %d bytes\n", sizeof(ptr));}

Output

[v i jai@ l ocal h os t pointer]$ gcc ptrtoptr.c[v i jai@ l ocal h os t pointer]$ ./a.outX value is 12 and stored at 3221220804

Pointer holds the address 3221220804Aceesing value thru pointer : 12Pointer is stored at location : 3221220800

Pointer-to-pointer holds the address 3221220800Accessing value thru ptr-to-ptr : 12

Size of ptr-to-ptr: 4 bytes

3.1.D—Addition using pointers

Algorithm

Step 1 : StartStep 2 : Read the values of a and bStep 3 : Assign the address of a and b to x and yStep 4 : Sum the values at locations pointed by x and y and store in cStep 5 : Print cStep 6 : Stop

Page 57: Ge 2155 Full

C Programming GE2155–Computer Practice II

Program (ptradd.c)

/* Addition operations using pointers */#include<stdio.h>main(){

int a,b,c; int *pa,*pb; pa=&a;pb=&b;printf("Enter values for A and B : ");scanf("%d%d",&a,&b); c = *pa + *pb; printf("Sum = %d\n",c);

}

Output

[v i jai@ l ocal h os t pointer]$ gcc ptradd.c[v i jai@ l ocal h os t pointer]$ ./a.outEnter values for A and B : 4 6Sum = 10

3.1.E—Basic Calculator

Algorithm

Step 1 : StartStep 2 : Read the values of a and bStep 3 : Assign the address of a and b to pointers pa and pbStep 4 : Display a simple calculator menuStep 5 : Based on user choice, perform arithmetic operations using pointer variablesStep 6 : Display the resultStep 7 : Stop

Program (ptrcalc.c)

/* Arithmetic operations using pointers */#include<stdio.h>main(){

int a,b,c; int *pa,*pb; char op; pa=&a;pb=&b;

printf("Basic Calculator");printf("\n + Addition");printf("\n - Subtraction");printf("\n * Multiplication");printf("\n / Quotient");

Page 58: Ge 2155 Full

C Programming GE2155–Computer Practice II

printf("\n % Remainder");printf("\n x Quit");printf("\nEnter operator : ");scanf("%c",&op);printf("Enter two integers : ");scanf("%d%d",&a,&b);

switch (op){

case '+':c = *pa + *pb;break;

case '-':c = *pa - *pb;break;

case '*':c = *pa * *pb;break;

case '/':c = *pa / *pb;break;

case '%':c = *pa % *pb;break;

default:

}exit(0);

printf(" %d %c %d = %d\n",a,op,b,c);}

Output

[v i jai@ l ocal h os t pointer]$ gcc ptrcalc.c[v i jai@ l ocal h os t pointer]$ ./a.outBasic Calculator

+ Addition- Subtraction* Multiplication/ Quotient% Remainder x Quit

Enter operator : +Enter two integers : 12 23

12 + 23 = 35

Page 59: Ge 2155 Full

C Programming GE2155–Computer Practice II

Ex. No: 3.2 Pointer Programming

AimTo study the advantages of using pointers in C programming.

Pointers & Function

Arguments passed to functions are pass 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 as pass by reference. Another use of pointers in function is that an address could be returned, known as return 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. The i+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, Xi+1,j+1 element couldbe 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.

ResultThus C programs using pointers were executed and its efficacy realized.

Page 60: Ge 2155 Full

C Programming GE2155–Computer Practice II

3.2.A—Pass 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 function swapref with parameters of type integer pointer that swaps two variables using a temporary variable and pointer notation

Step 3 : In main function get values of two variables, say a and bStep 4 : Call function swapval with a and b as arguments (Call by value) Step 5 : Print the values of a and b after function call.Step 6 : Call function swapref with address of a and b as arguments (Call by reference)Step 7 : Print the values of a and b after function call. Step 8 : Stop

Program (passbyref.c)

/* Pass by value and reference */#include <stdio.h>main(){

int a, b;void swapval(int, int); /* Pass by reference */void swapref(int *, int *); /* Pass by value */

printf("Enter the values of A and B : ");scanf("%d%d",&a,&b);

swapval(a,b); /* Call by value */ printf("\nValues after Pass by Value\n"); printf("Value of A is %d\n",a); printf("Value of B is %d\n",b);

swapref(&a, &b); /* Call by reference */ printf("\nValues after Pass by Reference\n"); printf("Value of A is %d\n",a);printf("Value of B is %d\n",b);

}

void swapref(int *x, int *y){

int t;t = *x;*x = *y;*y = t;

}void swapval(int a, int b){

int t; t = a; a = b; b = t;

}

Page 61: Ge 2155 Full

C Programming GE2155–Computer Practice II

Output

[v i jai@ l ocal h os t pointer]$ gcc passbyref.c[v i jai@ l ocal h os t pointer]$ ./a.outEnter the values of A and B : 12 23

Values after Pass by ValueValue of A is 12Value of B is 23

Values after Pass by ReferenceValue of A is 23Value of B is 12

3.2.B—Return 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, say a and bStep 3 : Call function big with address of a and b as arguments (Call by reference) Step 4 : Print value stored at the address returned

Program (retbyref.c)

/*Return by reference*/#include <stdio.h>int* big(int* x, int* y){

if (*x > *y)return x;

else

}return y;

main(){

int a, b;int *p;printf("Enter two values : ");scanf("%d%d",&a,&b); p = big(&a, &b); printf("Biggest is %d\n",*p);

}

Output

[v i jai@ l ocal h os t pointer]$ gcc retbyref.c[v i jai@ l ocal h os t pointer]$ ./a.outEnter two values : 3 7Biggest is 7

Page 62: Ge 2155 Full

C Programming GE2155–Computer Practice II

3.2.C—Sum of one-dimensional array

Algorithm

Step 1 : Declare an integer array and an integer pointer p. Step 2 : Get array elements using a for loopStep 3 : Assign starting address of the array to pStep 4 : Set up a loopStep 4.1 : Display the element’s value and address using *p and pStep 4.2 : Add elements value to sumStep 4.3 : Increment p by 1Step 5 : Display sumStep 6 : Stop

Program (array1d.c)

/* Pointers and one-dimensional arrays */#include <stdio.h>main(){

int i, n, sum=0;int x[25],*p;printf("Enter number of elements : ");scanf("%d",&n);printf("Enter Array elements : ");for(i=0; i<n; i++)

scanf("%d",&x[i]);

p = x; /* p points to array x */for(i=0; i<n; i++){

printf("x[%d] = %d stored at %u\n",i,*p,p);sum += *p;p++; /* Address incremented points to next element */

}printf("Sum = %d\n ",sum);

}

Output

[v i jai@ l ocal h os t pointer]$ gcc array1d.c[v i jai@ l ocal h os t pointer]$ ./a.outEnter number of elements : 5Enter Array elements : 12 23 34 45 56 x[0] = 12 stored at 3221218368x[1] = 23 stored at 3221218372 x[2] = 34 stored at 3221218376 x[3] = 45 stored at 3221218380 x[4] = 56 stored at 3221218384Sum = 170

Page 63: Ge 2155 Full

C Programming GE2155–Computer Practice II

3.2.D—Displaying 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 index i that iterates for rows.Step 3 : Set up a loop for the column index j that iterates for columns. Step 4 : Display the element using pointer notation as *(*(a + i) + j)) Step 5 : Stop

Program (2darray.c)

/* Pointers and 2-dimensional array */#include <stdio.h>main(){

int a[3][3]={{1,2,3}, {4,5,6}, {7,8,9}};int i,j;

for(i=0; i<3; i++){

for(j=0; j<3; j++){

printf("%4d", *(*(a+i)+j));}printf("\n");

}}

Output

[v i jai@ l ocal h os t pointer]$ gcc 2darray.c[vi jai@l ocalh ost pointer]$ ./a.out

1 2 34 5 67 8 9

3.2.E—String copy using pointers

Algorithm

Step 1 : Create function stringcopy with two parameters of type character pointer Step 2 : Set up a loop that iterates until the source string encounters a null character Step 2.1 : Assign the source string’s character to the destination stringStep 2.2 : Increment the source and destination strings address by 1Step 2.3 : Assign null character to the destination string Step 3 : In main function, declare two strings src and dest Step 4 : Get a string from the user for srcStep 5 : Call stringcopy function and pass the address of src and destStep 6 : Display dest stringStep 7 : Stop

Page 64: Ge 2155 Full

C Programming GE2155–Computer Practice II

Program (strcopy.c)

/* Copy strings using pointers */#include <stdio.h>main(){

void stringcopy(char*, char*);char src[80];char des[80];

printf("Enter a string : ");gets(src);stringcopy(des, src);printf("Copied string : %s\n", des);

}

void stringcopy(char *d, char *s){

while(*s){

*d = *s;s++;d++;

}*d = '\0';

}

Output

[v i jai@ l ocal h os t pointer]$ gcc strcopy.c[v i jai@ l ocal h os t pointer]$ ./a.outEnter a string : Self-conquest is the greatest victoryCopied string : Self-conquest is the greatest victory

3.2.F—Student Detail

Algorithm

Step 1 : Declare a student structure with members rollno, name and markStep 2 : Create a variable s1, and a pointer ptr of type studentStep 3 : Populate s1 with inputs from the userStep 4 : Assign address of s1 to ptrStep 5 : Display the values of structure members using pointer-to-member operatorStep 6 : Stop

Page 65: Ge 2155 Full

C Programming GE2155–Computer Practice II

Program (studdetail.c)

#include<stdio.h>struct student{

long rollno; char name[10]; float mark;

};

main(){

struct student *ptr;struct student s1;printf("\nEnter student’s rollno, name, mark : "); scanf("%ld%s%f",&s1.rollno,s1.name,&s1.mark); ptr=&s1;printf("\n\tSTUDENT DETAIL"); printf("\nRollno\tName\t\tMark\n"); printf("%ld\t%s\t%.2f\n",ptr->rollno,ptr->name,ptr->mark);

}

Output

[v i jai@ l ocal h os t pointer]$ gcc studdetail.c[v i jai@ l ocal h os t pointer]$ ./a.outEnter studentÆs rollno, name, mark : 1032957 Adhithan 10

STUDENT DETAILS Rollno Name Mark1032957 Adhithan 10.00

3.2.G—Employee Payroll

Algorithm

Step 1 : Declare a employee structure with members id, name, basic, hra, da, it, grossand netpay

Step 2 : Create array of structure employee as emp and a pointer ptr of type employeeStep 3 : Get number of employees as inputStep 4 : Set up a loop and for each employee obtain values for id, name and basicStep 5 : Set up a loop, and for each employeeStep 5.1 : Compute hra, da, it as given in the problem statementStep 5.2 : Compute gross= hra + daStep 5.3 : Compute netpay = gross - itStep 6 : Display header for employee payrollStep 7 : Assign address of emp to ptrStep 8 : Setup a loop and display employees data in a tabular format using ptrStep 9 : Stop

Page 66: Ge 2155 Full

C Programming GE2155–Computer Practice II

Program (payroll.c)

/* Payroll Generation */#include <stdio.h>struct employee{

int empid;char ename[15];int basic; float hra; float da; float it; float gross; float netpay;

};

main(){

struct employee emp[50], *ptr;int i, j, n;printf("Enter No. of Employees : ");scanf("%d", &n);for(i=0; i<n ;i++){

printf("\nEnter Employee Details\n"); printf("Enter Employee Id : "); scanf("%d", &emp[i].empid); printf("Enter Employee Name : "); scanf("%s", emp[i].ename); printf("Enter Basic Salary : "); scanf("%d", &emp[i].basic);

}ptr=emp;for(i=0; i<n; i++){

ptr->hra = 0.02 * ptr->basic; ptr->da = 0.01 * ptr->basic; ptr->it = 0.05 * ptr->basic;ptr->gross = ptr->basic+ptr->hra+ptr->da;ptr->netpay = ptr->gross - ptr->it;ptr++;

}

Page 67: Ge 2155 Full

C Programming GE2155–Computer Practice II

ptr=emp;printf("\n\n\n\t\t\t\tXYZ & Co. Payroll\n\n");for(i=0;i<80;i++)

printf("*");printf("\nEmpId\tName\t\tBasic\t HRA\t DA\t IT\tGross\t\tNet Pay\n\n");for(i=0;i<80;i++)

printf("*");

for(i=0; i<n; i++){

printf("\n%d\t%-15s\t%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f", ptr->empid, ptr->ename,ptr->basic,ptr->hra,ptr->da,ptr->it,ptr->gross, ptr->netpay);

ptr++;} printf("\n"); for(i=0;i<80;i++)

printf("*");}

Output

[v i jai@ l ocal h os t pointer]$ gcc studdetail.c[v i jai@ l ocal h os t pointer]$ ./a.outEnter No. of Employees : 2Enter Employee DetailsEnter Employee Id : 436Enter Employee Name : GopalEnter Basic Salary : 10000Enter Employee DetailsEnter Employee Id : 463Enter Employee Name : RajeshEnter Basic Salary : 22000

XYZ & Co. Payroll

*******************************************************************************

* EmpId Name Basic HRA DA IT Gross Net Pay

********************************************************************************

436 Gopal 10000 200.00 100.00 500.00 10300.00 9800.00463 Rajesh 22000 440.00 220.00 1100.00 22660.00 21560.00

********************************************************************************

Page 68: Ge 2155 Full

C Programming GE2155–Computer Practice II

Ex. No: 3.3 Dynamic Memory Allocation

AimTo 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 malloc, calloc and realloc, which can be used to allocate and free memory using free during the program execution.

The memory space located between program and local variable is available known as heap for dynamic allocat ion 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.

mallocThe malloc function reserves a block of memory of specified size and returns a pointer oftype 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*) malloc(bytesize);

calloccalloc is another memory allocation function that is normally used to request multiple blocksof storage each of the same size and then sets all bytes to zero.

ptr =(casttype*) calloc(blockcount, blocksize);

freeCompile time storage of a variable is allocated and released by the system in accordance withits 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.

free(ptr);

reallocThe 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 = realloc(ptr, newsize);

ResultThus memory requirements were allocated dynamically and released later.

Page 69: Ge 2155 Full

C Programming GE2155–Computer Practice II

3.3.A—Mark aggregate

Algorithm

Step 1 : Read number of students, say nStep 2 : Request memory dynamically to store marks of n students using malloc and store

the address in aStep 3 : If requested block of memory is not allocated then StopStep 4 : Set up a loop and read array elements ai

Step 5 : Initialize sum to 0Step 6 : Set up a loop and array elements ai to sum Step 7 : Compute mark aggregate and display it Step 8 : Release the requested memoryStep 9 : Stop

Program (dynalloc.c)

/* Dynamic Memory Allocation using malloc() */#include <stdlib.h>#include <malloc.h>#include <stdio.h>main(){

int n, i, *a;float avg, sum=0;printf("Enter the No. of students : ");scanf("%d", &n);

a = (int*) malloc(n * sizeof(int));if (a == NULL){

printf("\n memory allocations not possible");exit(-1);

}printf("Enter %d marks : ", n);for(i=0; i<n; i++){

scanf("%d",&a[i]);}for(i=0; i<n; i++)

sum += a[i];avg = sum / n;printf("Average mark : %.2f\n",avg);free(a);

}

Output

[v i jai@ l ocal h os t pointer]$ gcc dynalloc.c[v i jai@ l ocal h os t pointer]$ ./a.outEnter the No. of students : 6Enter 6 marks : 56 67 78 89 90 98Average mark : 79.67

Page 70: Ge 2155 Full

C Programming GE2155–Computer Practice II

3.3.B—String Reallocation

Algorithm

Step 1 : Declare a string buf and message of type character pointerStep 2 : Obtain text for buf from the userStep 3 : Request memory allocation for message based on length(buf) + 1 using mallocStep 4 : Copy contents of buf to messageStep 5 : Display message and its capacityStep 6 : Obtain another text for buf from the userStep 9 : Request memory reallocation for message based on length(buf) + 1 using reallocStep 11 : Copy contents of buf to messageStep 12 : Display message and its capacityStep 13 : Release the requested memory and Stop

Program (strrealloc.c)

/* Dynamic Reallocation for strings */#include <stdio.h>#include <stdlib.h>#include <string.h>main(){

char buf[80], *message;

printf("Enter text and press enter : ");gets(buf); /* Get a string from the user */

/* Allocate the initial block and copy the string to it. */message = (char*)malloc(strlen(buf)+1);strcpy(message, buf); printf("Content stored is : "); puts(message); /* Display the message. */printf("Initial allocation : %d bytes\n", strlen(message));

printf("Enter another text and press enter : ");gets(buf); /* Get another string from the user. */

/* Reallocate for the new string */message = (char *) realloc(message, strlen(buf) + 1);strcpy(message, buf);printf("Modified content is : ");puts(message); /* Display the new message. */printf("Reallocated memory : %d bytes\n", strlen(message));

free(message);}

Output

[v i jai@ l ocal h os t pointer]$ gcc strrealloc.c[v i jai@ l ocal h os t pointer]$ ./a.outEnter text and press enter : Hi!

Page 71: Ge 2155 Full

C Programming GE2155–Computer Practice II

Content stored is : Hi! Initial allocation : 4 bytesEnter another text and press enter : How r u? Modified content is : How r u?Reallocated memory : 8 bytes

3.3.C—Allocation for two dimensional array

Algorithm

Step 1 : Declare a pointer-to-pointer ptr variableStep 2 : Get number of rows and colsStep 3 : Request memory for ptr based on rows using calloc (Array of pointers) Step 4 : Set up a loop that iterates based on rowsStep 4.1 : Request memory for each array element of ptr based on cols using callocStep 5 : Set up a nested loop and display the 2D array with default valuesStep 6 : Release the requested memory and Stop

Program (2dcalloc.c)

/* Dynamic allocation for 2D array */#include <stdio.h>#include <malloc.h>

main(){

int i, j, row, col, **ptr;printf("Enter row and column dimension : ");scanf("%d%d",&row,&col);

/* 2d array is an array of pointers */ ptr = (int *) calloc(row, sizeof(int)); for(i=0; i<row; i++)

ptr[i] = (int *) calloc(col, sizeof(int));

/* Display default value 0 assigned due to calloc */for (i=0; i<row; i++){

for (j=0; j<col; j++)printf("%4d",ptr[i][j]);

printf("\n");}free(ptr);

}

Output

[v i jai@ l ocal h os t pointer]$ gcc 2dcalloc.c[v i jai@ l ocal h os t pointer]$ ./a.outEnter row and column dimension : 3 4

0 0 0 00 0 0 00 0 0 0

Page 72: Ge 2155 Full

C Programming GE2155–Computer Practice II

Ex. No: 3.4 File Handling

AimTo 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 FILE, 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

FILE *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, a NULL is returned.

fileptr = fopen("filename", "mode");

The file mode specifies the purpose of opening a file. Some of them are

Mode Descriptionr Open an existing file for reading onlyw Open a new file for writing only. If the file exists, its contents are destroyeda 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

The getc funct ion is used to read a character from the file opened in read mode and assigns it to a character variable. The getc will return an EOF 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 = getc(fileptr);putc(charvar, fileptr);

fgets & fputs

Rather than single characters, to deal with strings fgets and fputs are used in a similar manner.

Page 73: Ge 2155 Full

C Programming GE2155–Computer Practice II

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.

fread(&structvar, sizeof(structvar), 1, fileptr);fwrite(&structvar, sizeof(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 Descriptionftell Returns the number of bytes read or writtenrewind Resets the file pointer to start of the filefseek Moves the file pointer to the desired byte

fseek(fileptr, offset, position);position can take values 0, 1 or 2 indicating begining, current position, and endof 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.

fclose(fileptr);

ResultThus sequential and random disk I/O is executed using file handling functions.

Page 74: Ge 2155 Full

C Programming GE2155–Computer Practice II

3.4.A—Write to a file character-by-character

Algorithm

Step 1 : Declare a file pointer fpStep 2 : Open file CharFile.txt in write mode using fpStep 3 : If file could not be created then StopStep 4 : Read a character from the consoleStep 5 : If character is not end-of-file then write it onto file using putcStep 6 : Repeat steps 4 and 5 until end-of-file is encounteredStep 7 : Close the fileStep 8 : Stop

Program (chario.c)

/* File I/O using getc and putc functions */#include <stdio.h>#include <stdlib.h>main(){

FILE *fp;char c;

fp=fopen("CharFile.txt", "w");if (fp == NULL) {

printf("File not Accessible");exit(-1);

}

printf("Input Text--Ctrl + D to Terminate\n");/* Get data (char by char) from user and write onto file*/while( (c=getchar()) != EOF)

putc(c, fp);fclose(fp);

}

Output

[v i jai@ l ocal h os t files]$ gcc chario.c[v i jai@ l ocal h os t files]$ ./a.out Input Text--Ctrl + D to Terminate Welcome to File handlingA file should be opened before an I/O I/O should not conflict with the mode After I/O files should be closed [v i jai@ l ocal h os t files]$ cat CharFile.txt Welcome to File handlingA file should be opened before an I/OI/O should not conflict with the modeAfter I/O files should be closed

Page 75: Ge 2155 Full

C Programming GE2155–Computer Practice II

3.4.B—File Statistics

Algorithm

Step 1 : Declare a file pointer fp and static variables lc, wc, ccStep 2 : Open file CharFile.txt in read mode using fpStep 3 : Fetch a character from the fileStep 4 : Display the character and increment cc by 1Step 5 : If character is a newline then increment lc and wc by 1Step 6 : If character is a whitespace then increment wc by 1Step 7 : Repeat steps 3–6 until end-of-file is encounteredStep 8 : Display number of words, lines and characters in the fileStep 9 : Close the file and Stop

Program (filestat.c)

/* Statistics of file-word, lines, character */#include <stdio.h>main(){

FILE *fp;char c;static int lc, wc, cc;

/* File Read and process */fp=fopen("CharFile.txt", "r");while( (c=getc(fp)) != EOF ) /* Process char-by-char */{

switch(c) /* Count lines, words & character */{

case '\n' :++lc;++wc;break;

case ' ' :++wc;break;

default :++cc;

}}printf("No. of lines : %d", lc);printf("\nNo. of words : %d", wc);printf("\nNo. of characters (spaces excl.) : %d\n", cc);fclose(fp);

}

Output

[v i jai@ l ocal h os t files]$ gcc filestat.c[v i jai@ l ocal h os t files]$ ./a.outNo. of lines : 4

Page 76: Ge 2155 Full

C Programming GE2155–Computer Practice II

No. of words : 25No. of characters (spaces excl.) : 109

3.4.C—Employee Record

Algorithm

Step 1 : Declare structure employee with members code, name, design and basicStep 2 : Declare a file pointer fp and variables casual of type employeeStep 3 : Open file emp.dat in write mode using fpStep 4 : Set up a loop to input employee data until name='xxx'Step 4.1 : Get full details of an employee using casual with code auto-generatedStep 4.2 : Write casual onto file emp.dat using fwrite Step 5 : Display size of the file using ftell and close it Step 6 : Reopen file emp.dat in read mode using fpStep 7 : Get the employee code for which details are sought. Step 8 : Go to the start of the required data using fseekStep 9 : Load the employee details onto casual using fread and display itStep 10 : Close the file and Stop

Program (emprec.c)

/* Binary I/O using fwrite and random fread */#include <stdio.h>#include <string.h>

struct employee{

};

main(){

int code;char name[20]; char desig[20]; float basic;

struct employee casual, temp; FILE *fp;int id, eno,n,pos, lb;id = 1000;

fp = fopen("Emp.dat", "w"); printf("\tEnter employee details\n"); while (1){

casual.code=id++;printf("Employee Id : %d", casual.code); printf("\nEnter Name (xxx to quit) : "); scanf("%s", casual.name);if (strcmp(casual.name,"xxx") == 0)

break;printf("Enter Designation : ");

Page 77: Ge 2155 Full

C Programming GE2155–Computer Practice II

scanf("%s", casual.desig); printf("Enter Basic Salary: "); scanf("%f", &casual.basic);fwrite (&casual, sizeof(casual), 1, fp);

}n = ftell(fp);printf("\nFile size : %d bytes\n",n);fclose(fp);

/* Record seek */fp = fopen("Emp.dat", "r"); printf("\nEnter Employee id : "); scanf("%d",&eno);pos = (eno-1000)*sizeof(casual);if (pos < n){

}else

fseek(fp,pos,0);fread (&temp, sizeof(temp), 1, fp); printf("Employee Name : %s\n", temp.name); printf("Employee Designation : %s\n", temp.desig); printf("Employee Basic : %.2f\n", temp.basic);

printf("\nIncorrect Employee Id");fclose(fp);

}

Output

Enter employee detailsEmployee Id : 1000Enter Name (xxx to quit) : PrabakharEnter Designation : AnalystEnter Basic Salary: 34000Employee Id : 1001Enter Name (xxx to quit) : Raghu Enter Designation : Administrator Enter Basic Salary: 28000Employee Id : 1002Enter Name (xxx to quit) : Gokul Enter Designation : Programmer Enter Basic Salary: 25000Enter Name (xxx to quit) : xxx

File size : 150 bytes

Enter Employee id : 1001Employee Name : RaghuEmployee Designation : AdministratorEmployee Basic : 28000.00

Page 78: Ge 2155 Full

C Programming GE2155–Computer Practice II

Ex. No: 3.5 Command Line Arguments

AimTo 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.

main(int argc, char *argv[])

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:

x Arguments are delimited by white space, which is either a space or a tab.x A string surrounded by double quotation marks is interpreted as a single argument.x A double quotation mark preceded by a backslash, \", is interpreted as ".x Two back slashe (\\) is replaced by a single backslash (\).

For instance, the following command line is interpreted as

$./copy cnotes cpnotes

argc = 3argv[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.

ResultThus arguments were passed to programs at command line and executed

Page 79: Ge 2155 Full

C Programming GE2155–Computer Practice II

3.5.A—Listing command line arguments

Program (cmdline.c)

/* Command line arguments */#include <stdio.h>main(int argc, int *argv[]){

int i;printf("Number of arguments : %d\n", argc);for(i=0; i<argc; i++)

printf("Argument [%d] = %s\n",i, argv[i]);}

Output

[v i jai@ l ocal h os t files]$ gcc cmdline.c -o cmdline [v i jai@ l ocal h os t files]$ ./cmdline "C:\\Program Files\\Adobe" readme.txt Number of arguments : 3Argument [0] = ./cmdlineArgument [1] = C:\Program Files\AdobeArgument [2] = readme.txt

3.5.B—File copy

Program (filecopy.c)

/* File copy—imitating cp command */#include <stdio.h>#include <stdlib.h>main(int argc, char *argv[]) /* Command line arguments */{

FILE *src, *des;char ch;

if (argc != 3){

printf("Arguments insufficient\n"); printf("Usage : ./filecopy source dest\n"); exit(-1);

}src = fopen(argv[1], "r");if( src==NULL ){

printf("Source File not Acccessible\n");exit(-1);

}

Page 80: Ge 2155 Full

C Programming GE2155–Computer Practice II

des = fopen(argv[2], "w");if(des==NULL){

printf("Unable to create Destination file\n");exit(-1);

}

while (1){

ch=getc(src);if(ch==EOF)

break;else

putc(ch, des);}printf("File Copied\n");fclose(src);fclose(des);

}

Output

[v i jai@ l ocal h os t files]$ gcc filecopy.c -o filecopy [v i jai@ l ocal h os t files]$ ./filecopy Random.txt Arguments insufficientUsage : ./filecopy source dest[v i jai@ l ocal h os t files]$ ./filecopy Random.txt r.txtFile Copied[v i jai@ l ocal h os t files]$ lsa.out chario.c cmdline.c emprec.c filecopy.c random.c r.txt CharFile.txt cmdline Employee.txt filecopy filestat.c Random.txt [v i jai@ l ocal h os t files]$ cmp Random.txt r.txt [v i jai@ l ocal h os t files]$

3.5.C—Display file contents

Program (filecat.c)

/* Cat command */#include <stdio.h>main(int argc, char *argv[]){

FILE *fp;char c;

if(argc != 2){

fprintf(stderr, "Insufficient arguments\n"); fprintf(stderr, "Usage: ./filecat filename\n"); exit(-1);

}

Page 81: Ge 2155 Full

C Programming GE2155–Computer Practice II

fp = fopen(argv[1], "r");if(fp == NULL){

fprintf(stderr, "cat: can't open %s\n", argv[1]);exit(-1);

}

while((c = getc(fp)) != EOF)putchar(c);

fclose(fp);}

Output

[v i jai@ l ocal h os t files]$ gcc filecat.c -o filecat[v i jai@ l ocal h os t files]$ ./filecatInsufficient argumentsUsage: ./filecat filename[v i jai@ l ocal h os t files]$ ./filecat charfile.txt cat: can't open charfile.txt[vi jai@l ocalh ost files]$ ./filecat CharFile.txtWelcome to File handlingA file should be opened before an I/O I/O should not conflict with the mode After I/O files should be closed