0% found this document useful (0 votes)
3 views55 pages

UNIX & C Course Overview and Commands

The document outlines a comprehensive course description for a UNIX & C assignment, covering fundamental concepts, commands, and programming tasks related to the UNIX operating system. It includes questions and exercises on file management, permissions, shell commands, regular expressions, and scripting. The document serves as a guide for understanding UNIX functionalities and practical applications in programming.

Uploaded by

rajuvs18185
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views55 pages

UNIX & C Course Overview and Commands

The document outlines a comprehensive course description for a UNIX & C assignment, covering fundamental concepts, commands, and programming tasks related to the UNIX operating system. It includes questions and exercises on file management, permissions, shell commands, regular expressions, and scripting. The document serves as a guide for understanding UNIX functionalities and practical applications in programming.

Uploaded by

rajuvs18185
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

UNIX & C Assignment_QZ Course Description Document

These are not expected to be answered in writing, but as plug-ins for


the thorough understanding of the subject.

 Have you ever wondered how a system such as UNIX did ever come into
existence?
 What is that operating system in the computer systems you have now?
 Why Unix has become a popular operating system?
 How come Unix is so portable?
 Other features of Unix?
 Kernel?
 How does Unix view the devices?
 Types of UNIX Files
 Working with files and directories
 Default File and Directory permissions – Your umask
 Unix Commands?

ls, mkdir, cd, chmod


bc, dc—calculator programs
date and cal—to display time and date
finger, who and id—provide user information
man and help—explains commands
su—"switch user"
du and df—display information about disk contents

 Output/Input redirection
 What is a process?
 In which file is your password stored?
 What is the significance of passwd file?
 Metacharacters
 Regular Expressions
 Stream Editors
 How do we search for files in a directory structure?
 What is a shell?
 Bourne Shell
 Korn Shell
 C Shell
 Which is the Shell in your system?
 How and why do you program your shell?
 What are the popular editors with Unix?
 How does Linux differ from Unix?

TATA CONSULTANCY SERVICES For Internal Use Only Page 1 of 55


UNIX & C Assignment_QZ Course Description Document
pwd

When executed this gives the present working directory. Tells where a user is
presently situated. The response obtained is in the form of a path. The path
starts from the root directory.

1. What is meant by Absolute path?

2. What is meant by Relative path?

3. What are the paths that are included by default?

mkdir

To create a directory.

cd

Change Directory

4. What does cd do when used without arguments?

rmdir

To delete or remove a directory.

5. When will rmdir dir1 where dir1 is a directory fail to work?

6. What do the files . and .. mean?

7. Create a tree structure named ‘training’ in which there are 3 subdirectories –


‘level 1’,’ level2’ and ‘cep’. Each one is again further divided into 3. The ‘level
1’ is divided into ‘sdp’, ‘re’ and ‘se’. From the subdirectory ‘se’ how can one
reach the home directory in one step and also how to navigate to the
subdirectory ‘sdp’ in one step? Give the commands, which do the above
actions?

8. Give the commands to remove the directory training.

ls

Lists the contents of a directory.

9. How to give a long list of the files in the directory?

10. What are the different fields in the long listing of the directory?

11. What is the inode number of a file?

TATA CONSULTANCY SERVICES For Internal Use Only Page 2 of 55


UNIX & C Assignment_QZ Course Description Document
12. Give the command to list the files in the reverse alphabetical order.

13. How to get the listing of the directories recursively?

14. What does ‘ls –a’ do?

15. What does ‘ls –h’ do?

touch

Creates a zero byte file. Also used to modify the date and time of creating a file.

16. Create some files with the names ‘quiz’, feedback’, ‘test’ and ‘exam’.

cp

Copies one file onto another

ln

Gives different names to the same file.

17. What is the difference between cp and ln? Explain.

mv

Move the contents of a file onto another. (This is like rename in DOS).

18. What is the difference between cp and mv.

19. How will you copy a directory structure dir1 to dir2 ? (with all the
subdirectories)

rm

Deletes a file. Beware.

20. How to interactively remove a file?

21. How to remove a directory using ‘rm’ command?

chmod

Changing file permissions.

22. What does each digit in chmod signify?

23. Explain about each of the options along with chmod, namely, + - = etc. Try
out all these and compare.

TATA CONSULTANCY SERVICES For Internal Use Only Page 3 of 55


UNIX & C Assignment_QZ Course Description Document
24. What are the default permissions when a file or directory is created?

who

Gives the login details

25. How can you find out the number of users logged in?

26. How can you find out if you have the permission to send a message?

man

Online help for the commands executed.

27. How to get only the options and arguments of a command excluding the
descriptive help?

du

Summarises the disk usage of each file recursively for directories.

28. Find the space occupied ( in Bytes) by the /home directory including all its
subdirectories.

df

Report file system disk space usage.

clear

Clears the screen.

cat

Used to create, display and append to files.

29. How can cat be used to append to a file?

30. How do you get the numbered lines in the output?

more ( less is another pager available on Linux)

Paging output. The screen will handle one page at a time.

31. How do you count the number of logical lines?

32. How do you get the output screen by screen?

TATA CONSULTANCY SERVICES For Internal Use Only Page 4 of 55


UNIX & C Assignment_QZ Course Description Document
type

The location of the program is obtained.

cmp

To check whether two files are identical or not. The output of ‘cmp’, if the files
differ is the first position at which difference occurs.

33. When does ‘cmp’ command not give any response even when the files are
different?

diff

Displays the differences in two files/ directories.

34. What option can be used to get the answer to whether the files are different or
not?

35. When are the changes in cases ignored? ie, with what option?

comm

Finds out what is common in two sorted files.

36. How will you display only the lines common to two files?

umask

When file is created it is given some default permissions. The file permission
mask determines this. The default file permission mask can be found by typing
‘umask’ without any arguments at the command prompt.

37. What is your default file permission mask?

38. What is the mask value you will use if you want the owner of the to have
read/write permissions and everybody else to have nil permissions?

39. Can you create a file if the ‘umask’ is set to 777? Explain your answer

date

date command can be used to print the current date and time. Find out its details
of usage from the man pages and do the following:

40. What is the command for printing the current time in 24-hour format?

41. What is the command for printing the year, month, and date with a horizontal
tab between the fields?

TATA CONSULTANCY SERVICES For Internal Use Only Page 5 of 55


UNIX & C Assignment_QZ Course Description Document
cal

cal command prints the calendar.

42. What is the command for printing the calendar of the current month?

43. What is special about September 1752?

bc

Basic Calculator

44. Do all the basic arithmetic operations using bc.

wc

wc counts characters, words, and lines in a file.

45. What is the command for printing the number of lines in the ‘passwd’ file?

sort

sort sorts information alphabetically.

46. What are the commands used to sort some information in the reverse order
and in the numerical order?

47. What does the command sort –f do?

uniq

uniq is a filter which gives the unrepeated elements in a file.

48. What do the commands uniq –c, uniq –d and uniq –u do?

49. Can uniq be used on an unsorted file?

find

Search for files in a directory hierarchy.

50. Search for a file “[Link]” from the /home directory. It can exist in any of the
subsequent directories.

wild cards

The shell uses certain characters for pattern matching. For example ‘*’ is used to
match any character including none and ‘?’ matches a single character. Find out
more about these characters and answer the following.

TATA CONSULTANCY SERVICES For Internal Use Only Page 6 of 55


UNIX & C Assignment_QZ Course Description Document
51. First create the following files: chapa, chapb, chapc, chapd, chape, chapA,
chapB, chapC, chapD, chapE, chap01, chap02, chap03, chap04, chap05,
chap11, chap12, chap13, chap14, and chap15.

52. What is the command for listing all files ending in small letters?

53. What is the command for listing all files ending in capitals?

54. What is the command for listing all files whose last but one character is 0?

55. What is the command for listing all files which end in small letters but not ‘a’
and ‘c’?

redirection

Input and output can be redirected from stdin and stdout. ‘<’ symbol is used for
input redirection and ‘>’ symbol is used for output redirection.

56. What is the ‘>>’ symbol used for?

57. What is the command for sending the output to stdout and error messages to
the null device (or bit bucket)?

58. What is the command for sending both the output and the error messages to
the same file?

pipes

‘|’ is called the pipe symbol. With this the output of a command can be connected
to the input of another command. Any number of commands can be connected
this way. To save the output of any command in the middle of a pipe to a file tee
is used.

59. What is the command to print the number of users logged on to a system?

60. How do you connect two commands using tee?

61. Connect the two commands cat part1 part2 > total and lpr total using tee.

62. How to append to a file using tee?

TATA CONSULTANCY SERVICES For Internal Use Only Page 7 of 55


UNIX & C Assignment_QZ Course Description Document

vi

Type vilearn at the command prompt and go through all the lessons. You are
also expected to go through the chapters on editors in the book given to you.
Now answer the following:

63. What are the three modes of vi?

64. What is the command to introduce a new line above the first line in a file?

65. What is the command to replace an entire line?

66. What is the command to insert 50 dashes (‘-‘) in a line?

67. What is the expression you will use to match blank lines?

68. Assume you have deleted 5 lines from a file, 3 lines from another place, and 6
lines from somewhere else. What to do to paste the lines deleted second time
at the end of the file?

69. How do you join two lines?

70. How many named buffers are there in vi?

71. How do you append lines to a named buffer?

72. Where do you store the customization commands for vi?

TATA CONSULTANCY SERVICES For Internal Use Only Page 8 of 55


UNIX & C Assignment_QZ Course Description Document

REGULAR EXPRESSIONS

‘*’ character is used both as a shell wild card character and in regular
expressions. What is the difference in the interpretations?

73. How is the character ‘^’ used in a regular expression?

74. How is the character ‘$’ used in a regular expression?

grep, sed

grep is used to match patterns in a file.

75. ‘-v’ is one of the options that can used with grep. What does it do and what is
its usefulness?

76. In an organisation one wants to know how many programmers are there. The
employee data is stored in a file called ‘personnel’ with one record per
employee. Every record has field for designation. How can grep be used for
this purpose?

77. When is it necessary to put the string to be matched in quotes in grep?

sed is called stream editor

78. In the organisation mentioned above how can sed be used to print only the
records of all employees who are programmers.

79. In the organisation mentioned above how can sed be used to change the
designation ‘programmer’ to ‘software professional’ every where in the
‘personnel’ file

PROCESSES

80. How do you run a job in the background? How do you ensure that the job
does not get terminated when you logout?

81. Find out about the sleep command and start five jobs in the background, each
one sleeping for 10 minutes.

82. What is the command for printing a list of background jobs?

83. What is the command for bringing the 3rd background job to the foreground?
And how will you put it back in the background?

84. How do you kill the 3rd background job?

TATA CONSULTANCY SERVICES For Internal Use Only Page 9 of 55


UNIX & C Assignment_QZ Course Description Document

85. What will happen if you kill your login shell?

ps

This command makes a process status report.

86. How do you get the status of all the processes running on the system? i.e.
using what option?

87. How to get a long listing of all the process status details?

TATA CONSULTANCY SERVICES For Internal Use Only Page 10 of 55


UNIX & C Assignment_QZ Course Description Document

shell

set

This command makes the shell printout the variables it knows and also to assign
values to the positional parameters.

88. What does the command set seven days in a week do?

export

Allows copies of a variable and its value presented to different processes.

89. Give an example of making a variable available to all the processes using
export. Is it truly becoming available to all?

90. What command will change your prompt to ‘tcs’?

91. What are contents of the shell variables HOME and PATH?

92. What are the contents of the shell variables PWD and OLDPWD and how do
you use OLDPWD?

93. Is it possible to type more than one command at the shell prompt and how do
you do it?

94. It is possible to concatenate commands with ‘||’ and ‘&&’. What is their
purpose?

95. If you type the following at the shell prompt what happens and why?
cricketer=sachin tendulkar

echo can be used to print the contents of a shell variable or print a string . Find
out more about it from the man page.

96. What is the option to be used if do not want a new line to be output after the
echo?

97. Explain the differences between single quotes (‘), double quotes (“), and back
quotes (`)

98. Type the following at the shell prompt. What happens and how do you modify
it to get the desired output?
echo ‘the number of files in /bin directory are `ls –l /bin|wc –l` ‘

99. Enter the above statement in to a file called ‘[Link]’. What do you have to
do execute it?

TATA CONSULTANCY SERVICES For Internal Use Only Page 11 of 55


UNIX & C Assignment_QZ Course Description Document

100. How to execute the shell script in the same shell as it is operating from
and not in its child shell?

101. Write a script which accepts the word “tcs” as an answer regardless of
whether upper-case or lower-case letters are used anywhere in the word?

102. Write a script that asks for the capital of INDIA and repeats the question
until the user gets it right.

103. Write a script to print the number of command line arguments?

104. Write a script to print the command line arguments?

105. Modify the above script to test if the number of command line arguments
is zero and print a message if so?

106. Write a script which will take up to nine arguments, tests if each argument
is a readable file and prints a message?

107. How will you modify the above script if the number of arguments is greater
than nine?

Shell Programming Examples

1. Write a shell program, which when executed will ask you to enter your
name, once you give the input it comes up with the out "Hello < your name
>" on the screen.

2. Write a shell script, which will take two strings as input, compares them
and comes up with the output "Both are same" or "Both are different"
based on the inputs. It should also check for null string inputs and should
give corresponding error message.

3. Write a shell program, to print even & odd numbers from 1-50. The output
should look as follows:

ODD EVEN
===== ======
1 2
3 4
... ...
49 50

4. Write a shell program, to print prime numbers from 1-50. Don't worry
about the efficiency of the algorithm.

TATA CONSULTANCY SERVICES For Internal Use Only Page 12 of 55


UNIX & C Assignment_QZ Course Description Document

5. Write a shell program, which when executed will display following


messages base on the current system time:

For System Time Message To Be Displayed


============= ===================
06:00 - 11:59 a m Good Morning
12:00 Good Noon
12:01 - 03:00 p m Good Afternoon
03:01 - 10:00 p m Good Evening
10:01 - 05:59 a m Time To take rest , Good Night.

NOTE: You can add this to your ".profile" to get the message when
ever you login.

6. Without using UNIX line count command (e.g. wc ), write a shell script
which will print the no. of lines of a non-binary file.

7. Write a script to print the amount disk space used, in MBs (mega bytes) of
a current directory including all its sub-directory hierarchy. (Hint: Use "du"
command, du outputs no. of 512 byte blocks occupied by current
directory ).

8. Write a shell program, to send a message of text to all users who have
logged in as your user-id, without using UNIX communication commands.

(e.g.: if you have logged in as "user1", this script will send message all the
other sessions who are currently logged in as "user1". In fact this is a
restriction also that without using UNIX communication commands you
can't send message to any other users who have logged as different user-
id, why?
Hint: Strength of UNIX security feature. )

TATA CONSULTANCY SERVICES For Internal Use Only Page 13 of 55


UNIX & C Assignment_QZ Course Description Document

APPENDIX A
How to write a shell script
Introduction
A shell is a command line interpretor. It takes commands and executes them. As such, it
implements a programming language. The Bourne shell is used to create shell scripts -- ie.
programs that are interpreted/executed by the shell. You can write shell scripts with the C-shell;
however, this is not covered here.

Creating a Script
Suppose you often type the command
find . -name file -print
and you'd rather type a simple command, say
sfind file
Create a shell script
% cd ~/bin
% emacs sfind
% page sfind
find . -name $1 -print
% chmod a+x sfind
% rehash
% cd /usr/local/bin
% sfind tcsh
./shells/tcsh

Observations
This quick example is far from adequate but some observations:
1. Shell scripts are simple text files created with an editor.
2. Shell scripts are marked as executeable
%chmod a+x sfind
3. Should be located in your search path and ~/bin should be in your search path.
4. You likely need to rehash if you're a Csh (tcsh) user (but not again when you login).
5. Arguments are passed from the command line and referenced. For example, as $1.

#!/bin/sh
All Bourne Shell scripts should begin with the sequence
#!/bin/sh
From the man page for exec(2):
"On the first line of an interpreter script, following the "#!", is the name of a program which
should be used to interpret the contents of the file. For instance, if the first line contains "#!
/bin/sh", then the con- tents of the file are executed as a shell script."
You can get away without this, but you shouldn't. All good scripts state the interpretor explicitly.
Long ago there was just one (the Bourne Shell) but these days there are many interpretors -- Csh,
Ksh, Bash, and others.

Comments
Comments are any text beginning with the pound (#) sign. A comment can start anywhere on a
line and continue until the end of the line.

TATA CONSULTANCY SERVICES For Internal Use Only Page 14 of 55


UNIX & C Assignment_QZ Course Description Document

Search Path
All shell scripts should include a search path specifica- tion:
PATH=/usr/ucb:/usr/bin:/bin; export PATH
A PATH specification is recommended -- often times a script will fail for some people because
they have a different or incomplete search path.
The Bourne Shell does not export environment variables to children unless explicitly instructed to
do so by using the export command.

Argument Checking
A good shell script should verify that the arguments sup- plied (if any) are correct.

if [ $# -ne 3 ]; then
echo 1>&2 Usage: $0 19 Oct 91
exit 127
fi
This script requires three arguments and gripes accordingly.

Exit status
All Unix utilities should return an exit status.
# is the year out of range for me?

if [ $year -lt 1901 -o $year -gt 2099 ]; then


echo 1>&2 Year \"$year\" out of range
exit 127
fi

etc...

# All done, exit ok

exit 0
A non-zero exit status indicates an error condition of some sort while a zero exit status indicates
things worked as expected.
On BSD systems there's been an attempt to categorize some of the more common exit status
codes. See /usr/include/sysexits.h.

Using exit status


Exit codes are important for those who use your code. Many constructs test on the exit status of a
command.
The conditional construct is:
if command; then
command
fi
For example,
if tty -s; then
echo Enter text end with \^D
fi
Your code should be written with the expectation that others will use it. Making sure you return a
meaningful exit status will help.

TATA CONSULTANCY SERVICES For Internal Use Only Page 15 of 55


UNIX & C Assignment_QZ Course Description Document
Stdin, Stdout, Stderr
Standard input, output, and error are file descriptors 0, 1, and 2. Each has a particular role and
should be used accordingly:
# is the year out of range for me?

if [ $year -lt 1901 -o $year -gt 2099 ]; then


echo 1>&2 Year \"$year\" out of my range
exit 127
fi

etc...

# ok, you have the number of days since Jan 1, ...

case `expr $days % 7` in


0)
echo Mon;;
1)
echo Tue;;

etc...
Error messages should appear on stderr not on stdout! Output should appear on stdout. As for
input/output dialogue:
# give the fellow a chance to quit

if tty -s ; then
echo This will remove all files in $* since ...
echo $n Ok to procede? $c; read ans
case "$ans" in
n*|N*)
echo File purge abandoned;
exit 0 ;;
esac
RM="rm -rfi"
else
RM="rm -rf"
fi
Note: this code behaves differently if there's a user to communicate with (ie. if the standard input
is a tty rather than a pipe, or file, or etc. See tty(1)).

Language Constructs
For loop iteration
Substitute values for variable and perform task:
for variable in word ...
do
command
done
For example:
for i in `cat $LOGS`
do
mv $i $i.$TODAY
cp /dev/null $i
chmod 664 $i

TATA CONSULTANCY SERVICES For Internal Use Only Page 16 of 55


UNIX & C Assignment_QZ Course Description Document
done
Alternatively you may see:
for variable in word ...; do command; done
 Case
Switch to statements depending on pattern match
case word in
[ pattern [ | pattern ... ] )
command ;; ] ...
esac
For example:

case "$year" in

[0-9][0-9])
year=19${year}
years=`expr $year - 1901`
;;
[0-9][0-9][0-9][0-9])
years=`expr $year - 1901`
;;
*)
echo 1>&2 Year \"$year\" out of range ...
exit 127
;;
esac
 Conditional Execution
Test exit status of command and branch
if command
then
command
[ else
command ]
fi
For example:
if [ $# -ne 3 ]; then
echo 1>&2 Usage: $0 19 Oct 91
exit 127
fi
Alternatively you may see:
if command; then command; [ else command; ] fi
 While/Until Iteration
Repeat task while command returns good exit status.
{while | until} command
do
command
done
For example:
# for each argument mentioned, purge that directory

while [ $# -ge 1 ]; do
_purge $1
shift
done
Alternatively you may see:
while command; do command; done
 Variables
TATA CONSULTANCY SERVICES For Internal Use Only Page 17 of 55
UNIX & C Assignment_QZ Course Description Document
Variables are sequences of letters, digits, or underscores beginning with a letter or
underscore. To get the contents of a variable you must prepend the name with a $.
Numeric variables (eg. like $1, etc.) are positional vari- ables for argument
communication.
 Variable Assignment
Assign a value to a variable by variable=value. For example:
PATH=/usr/ucb:/usr/bin:/bin; export PATH
or
TODAY=`(set \`date\`; echo $1)`
 Exporting Variables
Variables are not exported to children unless explicitly marked.
# We MUST have a DISPLAY environment variable

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


if tty -s ; then
echo "DISPLAY (`hostname`:0.0)? \c";
read DISPLAY
fi
if [ "$DISPLAY" = "" ]; then
DISPLAY=`hostname`:0.0
fi
export DISPLAY
fi
Likewise, for variables like the PRINTER which you want hon- ored by lpr(1).
From a user's .profile:
PRINTER=PostScript; export PRINTER
Note: that the Cshell exports all environment variables.
 Referencing Variables
Use $variable (or, if necessary, ${variable}) to reference the value.
# Most user's have a /bin of their own

if [ "$USER" != "root" ]; then


PATH=$HOME/bin:$PATH
else
PATH=/etc:/usr/etc:$PATH
fi
The braces are required for concatenation constructs.
$p_01
The value of the variable "p_01".
${p}_01
The value of the variable "p" with "_01" pasted onto the end.
 Conditional Reference
${variable-word}
If the variable has been set, use it's value, else use word.
POSTSCRIPT=${POSTSCRIPT-PostScript};
export POSTSCRIPT

${variable:-word}
If the variable has been set and is not null, use it's value, else use word.
These are useful constructions for honoring the user envi- ronment. Ie. the user of
the script can override variable assignments. Cf. programs like lpr(1) honor the
PRINTER environment variable, you can do the same trick with your shell
scripts.

${variable:?word}
If variable is set use it's value, else print out word and exit. Useful for bailing out.
TATA CONSULTANCY SERVICES For Internal Use Only Page 18 of 55
UNIX & C Assignment_QZ Course Description Document
 Arguments
Command line arguments to shell scripts are positional vari- ables:
$0, $1, ...
The command and arguments. With $0 the command and the rest the arguments.
$#
The number of arguments.
$*, $@
All the arguments as a blank separated string. Watch out for "$*" vs. "$@".
And, some commands:
shift
Shift the postional variables down one and decrement number of arguments.
set arg arg ...
Set the positional variables to the argument list.
Command line parsing uses shift:
# parse argument list

while [ $# -ge 1 ]; do
case $1 in
process arguments...
esac
shift
done
A use of the set command:
# figure out what day it is

TODAY=`(set \`date\`; echo $1)`

cd $SPOOL

for i in `cat $LOGS`


do
mv $i $i.$TODAY
cp /dev/null $i
chmod 664 $i
done
 Special Variables
$$
Current process id. This is very useful for constructing temporary files.
tmp=/tmp/cal0$$
trap "rm -f $tmp /tmp/cal1$$ /tmp/cal2$$"
trap exit 1 2 13 15
/usr/lib/calprog >$tmp

$?
The exit status of the last command.
$command
# Run target file if no errors and ...

if [ $? -eq 0 ]
then
etc...
fi

 Quotes/Special Characters
Special characters to terminate words:
; & ( ) | ^ < > new-line space tab
TATA CONSULTANCY SERVICES For Internal Use Only Page 19 of 55
UNIX & C Assignment_QZ Course Description Document
These are for command sequences, background jobs, etc. To quote any of these use a
backslash (\) or bracket with quote marks ("" or '').
Single Quotes
Within single quotes all characters are quoted -- including the backslash. The result is one
word.

grep :${gid}: /etc/group | awk -F: '{print $1}'


Double Quotes
Within double quotes you have variable subsitution (ie. the dollar sign is interpreted) but
no file name generation (ie. * and ? are quoted). The result is one word.
if [ ! "${parent}" ]; then
parent=${people}/${group}/${user}
fi
Back Quotes
Back quotes mean run the command and substitute the output.

if [ "`echo -n`" = "-n" ]; then


n=""
c="\c"
else
n="-n"
c=""
fi
and
TODAY=`(set \`date\`; echo $1)`
 Functions
Functions are a powerful feature that aren't used often enough. Syntax is
name ()
{
commands
}
For example:

# Purge a directory

_purge()
{
# there had better be a directory

if [ ! -d $1 ]; then
echo $1: No such directory 1>&2
return
fi

etc...
}
Within a function the positional parmeters $0, $1, etc. are the arguments to the function
(not the arguments to the script).
Within a function use return instead of exit.
Functions are good for encapsulations. You can pipe, redi- rect input, etc. to functions.
For example:
# deal with a file, add people one at a time

do_file()
{
while parse_one
TATA CONSULTANCY SERVICES For Internal Use Only Page 20 of 55
UNIX & C Assignment_QZ Course Description Document

etc...
}

etc...

# take standard input (or a specified file) and do it.

if [ "$1" != "" ]; then


cat $1 | do_file
else
do_file
fi
 Sourcing commands
You can execute shell scripts from within shell scripts. A couple of choices:
sh command
This runs the shell script as a separate shell. For example, on Sun machines in /etc/rc:
sh /etc/[Link]
. command
This runs the shell script from within the current shell script. For example:
# Read in configuration information
. /etc/hostconfig
What are the virtues of each? What's the difference? The second form is useful for
configuration files where environment variable are set for the script. For example:
for HOST in $HOSTS; do

# is there a config file for this host?

if [ -r ${BACKUPHOME}/${HOST} ]; then
. ${BACKUPHOME}/${HOST}
fi
etc...
Using configuration files in this manner makes it possible to write scripts that are
automatically tailored for differ- ent situations.

Some Tricks
 Test
The most powerful command is test(1).
if test expression; then

etc...
and (note the matching bracket argument)
if [ expression ]; then

etc...
On System V machines this is a builtin (check out the com- mand /bin/test).
On BSD systems (like the Suns) compare the command /usr/bin/test with /usr/bin/[.
Useful expressions are:
test { -w, -r, -x, -s, ... } filename
is file writeable, readable, executeable, empty, etc?

test n1 { -eq, -ne, -gt, ... } n2


are numbers equal, not equal, greater than, etc.?
test s1 { =, != } s2
Are strings the same or different?
TATA CONSULTANCY SERVICES For Internal Use Only Page 21 of 55
UNIX & C Assignment_QZ Course Description Document
test cond1 { -o, -a } cond2
Binary or; binary and; use ! for unary negation.
For example
if [ $year -lt 1901 -o $year -gt 2099 ]; then
echo 1>&2 Year \"$year\" out of range
exit 127
fi
Learn this command inside out! It does a lot for you.
 String matching
The test command provides limited string matching tests. A more powerful trick is to
match strings with the case switch.
# parse argument list

while [ $# -ge 1 ]; do
case $1 in
-c*) rate=`echo $1 | cut -c3-`;;
-c) shift; rate=$1 ;;
-p*) prefix=`echo $1 | cut -c3-`;;
-p) shift; prefix=$1 ;;
-*) echo $Usage; exit 1 ;;
*) disks=$*; break ;;
esac

shift

done
Of course getopt would work much better.
 SysV vs BSD echo
On BSD systems to get a prompt you'd say:
echo -n Ok to procede?; read ans
On SysV systems you'd say:
echo Ok to procede? \c; read ans
In an effort to produce portable code we've been using:
# figure out what kind of echo to use

if [ "`echo -n`" = "-n" ]; then


n=""; c="\c"
else
n="-n"; c=""
fi

etc...

echo $n Ok to procede? $c; read ans


 Is there a person?
The Unix tradition is that programs should execute as qui- etly as possible. Especially for
pipelines, cron jobs, etc.
User prompts aren't required if there's no user.
# If there's a person out there, prod him a bit.

if tty -s; then


echo Enter text end with \^D
fi
The tradition also extends to output.
# If the output is to a terminal, be verbose

TATA CONSULTANCY SERVICES For Internal Use Only Page 22 of 55


UNIX & C Assignment_QZ Course Description Document
if tty -s <&1; then
verbose=true
else
verbose=false
fi
Beware: just because stdin is a tty that doesn't mean that stdout is too. User prompts
should be directed to the user terminal.
# If there's a person out there, prod him a bit.

if tty -s; then


echo Enter text end with \^D >&0
fi
Have you ever had a program stop waiting for keyboard input when the output is directed
elsewhere?
 Creating Input
We're familiar with redirecting input. For example:
# take standard input (or a specified file) and do it.

if [ "$1" != "" ]; then


cat $1 | do_file
else
do_file
fi
alternatively, redirection from a file:
# take standard input (or a specified file) and do it.

if [ "$1" != "" ]; then


do_file < $1
else
do_file
fi
You can also construct files on the fly.
rmail bsmtp <
rcpt to:
data
from: <$1@[Link]>
to:
Subject: Signon $2

subscribe $2 Usenet Feeder at UWO


.
quit
EOF
Note: that variables are expanded in the input.
 String Manipulations
One of the more common things you'll need to do is parse strings. Some tricks

TIME=`date | cut -c12-19`

TIME=`date | sed 's/.* .* .* \(.*\) .* .*/\1/'`

TIME=`date | awk '{print $4}'`

TIME=`set \`date\`; echo $4`

TIME=`date | (read u v w x y z; echo $x)`


TATA CONSULTANCY SERVICES For Internal Use Only Page 23 of 55
UNIX & C Assignment_QZ Course Description Document
With some care, redefining the input field separators can help.

#!/bin/sh
# convert IP number to [Link] name

name()
{ set `IFS=".";echo $1`
echo $4.$3.$2.$[Link]
}

if [ $# -ne 1 ]; then
echo 1>&2 Usage: bynum IP-address
exit 127
fi

add=`name $1`

nslookup < < EOF | grep "$add" | sed 's/.*= //'


set type=any
$add
EOF
 Debugging
The shell has a number of flags that make debugging easier:
sh -n command
Read the shell script but don't execute the commands. IE. check syntax.
sh -x command
Display commands and arguments as they're executed. In a lot of my shell scripts you'll
see
# Uncomment the next line for testing
# set -x

TATA CONSULTANCY SERVICES For Internal Use Only Page 24 of 55


UNIX & C Assignment_QZ Course Description Document

Problem Solving in ‘C’


Basic Building Blocks

1. Write a C program that does the following.

Take the number of items made in an hour as input. Compute number of


items made in a day and display. Assume an 8 hour day and same
number of items made in each hour.

As you can see from the program you have written, any C program is built using
the basic building blocks like Keywords, Constants, Operators, Variables,
Identifiers, Data types and Special symbols.

2. Categorise the following into like Keywords, Constants, Operators,


Variables, Identifiers, Data types, Special symbols and any other symbol.

main : printf :

scanf : for :

char : stdio.h :

#include : struct :

“a” : EOF :

‘a’ : while :

NULL : switch :

#define : typedef :

if : FILE :

“This is a statement” : sizeof :

{} : ():

‘‘: ; :

3. Is there any component /symbol in your program which does not belong to
any of these categories ? If yes, mention the symbol(s).

4. Constants are of type numeric constants, character/string constants


and ____________________

5. What are the differences between ‘a’ and “a”? How is each of
these stored in the memory ? How do you declare variables for containing
these two values ?

6. What is the output of the following program ?


TATA CONSULTANCY SERVICES For Internal Use Only Page 25 of 55
UNIX & C Assignment_QZ Course Description Document
/* Program # 1*/

#include <stdio.h>

/* Program to illustrate some operators and their precedences


*/

main()
{

int a = 1, b = 2, c =3;

c += ( a > 0 && a<= 10) ? ++a : a/b;

printf(“%d\n”, c);

}
7. Identify the various operators used in this program. Classify them
into unary, binary and ternary operators.

8. What does the following program do ? How are the output values
related to the input value given ?
/* Program # 2*/

/* Program illustrating bitwise operators */


#include <stdio.h>

main()
{
int integer, temp, count = 0, bit, word;
unsigned int mask;

printf(“Enter an integer as input\n”);


scanf (“%d”, &integer);

temp = integer;

for (count =0; temp != 0; temp = temp >> 1)


if (temp & 01)
count ++;
printf (“Count = %d\n”, count);

mask = 1;
word = 8 * sizeof(int);

mask = mask << (word – 1);

for (count = 1; count <= word; count ++)


{
bit = (integer & mask) ? 1 : 0;
printf (“%d”, bit);
mask >>= 1;
}
printf(“\n”);

TATA CONSULTANCY SERVICES For Internal Use Only Page 26 of 55


UNIX & C Assignment_QZ Course Description Document
}
9. Datatypes can be classified as Primary and Secondary. What are
secondary data types ? Give two examples for both.

10. What does the following program do ?


/* Program # 3*/

#include <stdio.h>

main()
{
unsigned int x ;

for (x=100; x >= 0 ; x-- )


{
printf(“%d\n”, x);
}
}

In C, various constructs cause the control flow in different ways. Statements in C can be
sequential, conditional (branching), iterative or jump statements.
[Link] examples of each of these constructs.

Sequential :

Conditional (Branching) :

Iterative :

Jump :

[Link] is the output of the following program? Explain.


/* Program # 4*/

#include <stdio.h>

void main ()
{
float a = 1.2, b = 2.1, c = 3.5:
float k;

printf (“Enter the number from the set (1.2, 2.1, 3.5)”);
scanf (“%f”, &k);

switch (k)
{
case 1.2 : printf(“First”);
break;
case 2.1 : printf (“Second”);
break;
case 3.5 : printf (“Third”);
break;
default : printf (“You have entered a wrong number”);
}
TATA CONSULTANCY SERVICES For Internal Use Only Page 27 of 55
UNIX & C Assignment_QZ Course Description Document
}

[Link] does the following program do ?

/* Program # 5*/

#include <stdio.h>

main()
{ int a, b;
scanf(“%d”, &a); printf(“\n%d”, a * 8);
}

Now, look at the program given below.

/* Program # 6 */

/* Program to take the no. of items made in an hour and compute


the no. of items made in an 8 hour day and display */

#include < stdio.h>


#define HOURS_PER_DAY 8;

main ()
{

int items_per_hour, items_per_day = 0;

printf(“\nGive the no. of items made per hour\n”);


scanf(“%d”, &items_per_hour); /* take the no. of items made per
hour as input */

/* Compute the no. of items made in a day */


items_per_day = items_per_hour * HOURS_PER_DAY;

/* Display items made per day as output */


printf (“\nThe no. of items made per day is %d\n”,
items_per_day);

Compare the above two programs (Program #5 and Program #6).


Compare first program you wrote (Qn. #1) with Program #6.

[Link] a look at TCS C Programming Standards available in the


library.
Rewrite your program in such a way that it confirms to the standards.
Why do you think that Standards are required ?
TATA CONSULTANCY SERVICES For Internal Use Only Page 28 of 55
UNIX & C Assignment_QZ Course Description Document

It has to be made a habit to follow programming standards. Please take care that
you follow the TCS C programming Standards in all the programs you write from
now on.

(The illustrative programs used in this assignment have not been written according to
TCS C Programming Standards. It has been done so for the sake of simplicity. But all the
programs written for production environment have to be conforming to standards.)

[Link] at Program # 6. How does it handle the following inputs ?

a) 20 :
b) 0:
c) –25 :
d) 3.5 :
e) ‘x’ :
f) 30xy :
g) 123456789012345 :

Does the program give logically incorrect output (e.g. a negative value for the
number of items made in a day) for any of the above inputs ? Or does it give
runtime error for any input ?

If the answer to any of the above questions is ‘Yes’, it is said that the program is not
defensive. That is, a defensive program behaves logically for any input. The program
should be able to distinguish between valid and invalid inputs. For the input 30xy, the
program will take 30 as input and give 240 as output. That is also not acceptable since the
program is not expected to manipulate the input given by the user. The program should
give an error message for all invalid inputs.

[Link] to make the program you have written for Qn. # 1 a defensive
one, so as to handle all the above inputs.

Look at the following program


/* Program # 7*/

#include < stdio.h>


#define HOURS_PER_DAY 8;

main ()
{

int items_per_hour, items_per_day = 0,


int count, valid_int;
char input[20];

/* take input till a valid input is given */


do
{

TATA CONSULTANCY SERVICES For Internal Use Only Page 29 of 55


UNIX & C Assignment_QZ Course Description Document
printf(“\nGive the no. of items made per hour\n”);

/* take the no. of items made per hour as input */


scanf(“%s”, input);

/* validate for non – digit characters in the input string and


for the length of the string. A maximum of 8 digits is assumed */

count = 0;
valid_int = 1;

while ((valid_int ==1) && (input[count] != ‘\0’)) /* a string


constant in ‘C’ is terminated by ‘\0’ */
{
if ( (input[count] <‘0’) || (input [count] > ‘9’)
|| (count >= 8) )

valid_int = 0;

else count ++;


}/*end–while((valid_int ==1)&&(input[count]!= ‘\0’)) */

/* Give error message if input is invalid */


if ( valid_int == 0)
printf (“\nThe given input is invalid. Please try again\
n”);

}while (valid_int == 0);


/* convert the string input to equivalent integer value */
items_per_hour = atoi(input);

/* Compute the no. of items made in a day */


items_per_day = items_per_hour * HOURS_PER_DAY;

/* Display items made per day as output */


printf (“\nThe no. of items made per day is %d\n”, items_per_day);

Now look at a different version of Program # 7


/* Program # 8*/

/* Program to take the no. of items made in an hour and compute the no.
of items made in an 8 hour day and display */

#include < stdio.h>


#define HOURS_PER_DAY 8;

int get_valid_int(char []);

main ()
{

int items_per_hour, items_per_day = 0;


char input[20];

/* take input till a valid input is given */


do
{
printf(“\nGive the no. of items made per hour\n”);
TATA CONSULTANCY SERVICES For Internal Use Only Page 30 of 55
UNIX & C Assignment_QZ Course Description Document

/* take the no. of items made per hour as input */


scanf(“%s”, input);

items_per_hour = get_valid_int(input);

/* Give error message if input is invalid */


if (items_per_hour == -1)

printf (“\nThe given input is invalid. Please try


again\n”);

}while (items_per_hour == -1);

/* Compute the no. of items made in a day */


items_per_day = items_per_hour * HOURS_PER_DAY;

/* Display items made per day as output */


printf (“\nThe no. of items made per day is %d\n”, items_per_day);

/* function get_valid_int validates for non – digit characters in the


input string and for the length of the string. A maximum of 8 digits is
assumed */

int get_valid_int(char input[])


{

int count = 0;

while (input[count] != ‘\0’)


{
if ( (input[count] <‘0’) || (input [count] > ‘9’) || (count
>= 8) )
{
return (-1);
}
else count ++;
} /* end – while (input[count] != ‘\0’) */

/* convert the valid input to the equivalent integer and return


the integer */
return (atoi(input));
}

Compare the above programs # 7 and # 8 . Program # 8 is a modular version of


program # 7. You can see that modularity has enhanced the readability,
understandability, flexibility and reusability of the code.

Make sure that all the programs you write from now are defensive, modular
and conforming to TCS standards.

Functions

As you can see from all the above programs, all ‘C’ programs are built of one or more
functions. Any ‘C’ program will consist of at least one function – the main() function.
TATA CONSULTANCY SERVICES For Internal Use Only Page 31 of 55
UNIX & C Assignment_QZ Course Description Document

In the above program the function main() calls the function get_valid_int() by
invoking it through the statement

items_per_hour = get_valid_int(input);

The calling function (main(), in the above program) and the called
function(get_valid_int() ) communicate between each other through parameters or
arguments and return values.

[Link] are the parameters used in the program # 8 ?

[Link] is the return value ?

[Link] the purpose of a function prototype declaration in a


program.

Use of functions enables readability, understandability, flexibility and reusability.

Recursion

Expressing an entity in terms of itself is called recursion. In C, a recursive function is a


function calling itself one or more times.

See the following example of a recursive function.

/* Program # 9*/

#include <stdio.h>

void myprint(int);

main()
{
myprint(0);
}

void myprint(int i)
{
if (i<5)
{
myprint(++i);
printf("%d ", i);
}
}

[Link] is the output of the above program ? When does the


recursion stop in this program ?

The following two important conditions must satisfied in any recursive function.
 Each time a function calls itself it must be closer, in some sense, to a solution.
 There must be a decision criterion for stopping the process or computation. This
criterion is also called the escape hatch or the base case.
TATA CONSULTANCY SERVICES For Internal Use Only Page 32 of 55
UNIX & C Assignment_QZ Course Description Document

[Link] the decision criterion for stopping in the above program.

[Link] a program to find the factorial for any given integer n. The
program should use a recursive function for finding the factorial.

Arrays
We have used a character array to take the input in program #7 and #8.
An array is a collection of objects of same data type stored in logically contiguous
locations. In the above program ‘input’ is a character array of size 20. The array index
varies from 0 to 19.

[Link] the function main() in program #8 so that it takes and


stores number of items made per hour by each of 10 employees in
a factory department. Compute and display the total no. of items
per employee per day in the factory and the grand total. The
function get_valid_int() need not be rewritten.

Pointers

A pointer is an address of a variable (memory location). That is, instead of being a


variable, it is a pointer(address) to a variable stored somewhere in the address space of
the program. The size of a pointer variable is the size of the address.

See the following example.


/* Program # 10 */

/* Program to illustrate use of pointer */

#include <stdio.h>

void main()

{
/* declare an integer variable index and two pointers pt1 and pt2. pt1
and pt2 are pointers to int */

int index, *pt1, *pt2;

/* variable index is assigned a numerical value */


index = 39;

/* pointer variable pt1 is being made to point to (contain )the


address of index */
pt1 = &index;

/* pointer variable pt2 also is being made to point to (contain )the


address of index */
pt2 = pt1;

printf("The values are index = %d *pt1 = %d *pt2 = %d\n", index,


*pt1, *pt2);

TATA CONSULTANCY SERVICES For Internal Use Only Page 33 of 55


UNIX & C Assignment_QZ Course Description Document

/* This changes the value of the location pointed by pt1, i.e.,


index */
*pt1 = 13;

printf("The values are index = %d *pt1 = %d *pt2 = %d\n", index,


*pt1, *pt2);
}

24. How does the output of the above program look ? Try to explain the
behaviour of the program.

Three important rules

1. A variable name with an ampersand (&) in front of it defines the address of


the variable and therefore points to the variable.
You can therefore read line pt1 = &index; as "pt1 is assigned the value of the
address of index".
2. A variable with a star (*) in front of it refers to the value of the variable
pointed to by the pointer variable. Line *pt1 = 13; of the program can be
read as "The stored (starred) value to which the pointer pt1 points is assigned
the value 13".
3. Initially, when a pointer is declared, it may be pointing to some unknown
location. We have to make it point to a meaningful location or contain NULL
by appropriately initialising it. Alternatively, we can allocate a new location
and make the pointer point to this location by using malloc()as illustrated
below.

/* Program # 11 */

#include <stdio.h>
main()
{
int *pt1;

/* Allocate memory for an int and return the address to pt1 */


pt1 = (int *) malloc(sizeof(int) );

printf(“Enter an integer \n”);


scanf(“%d”, pt1);;

printf(“\nThe integer value is %d\n”, *pt1);


}

[Link] does the above program do ? What is its output ?

TATA CONSULTANCY SERVICES For Internal Use Only Page 34 of 55


UNIX & C Assignment_QZ Course Description Document
[Link] happens if the line pt1 = (int *) malloc(sizeof(int)); is
omitted ?

Tips to remember

[Link] of & as an address.


[Link] of * as a star referring to stored value.

Arrays & Pointers

Arrays and Pointers can be synonymously used. Look at the following program.
/* Program # 12 */

/* Program to illustrate the synonymous use of arrays and pointers */

#include <stdio.h>

main()
{
char name_arr[12];
char *name_ptr;
printf(“\nEnter your name :”);
scanf(“%s”, name_arr);
name_ptr = name_arr;
printf(“The values are : name_arr - %s, name_ptr - %s\n”, name_arr,
name_ptr);

[Link] is the output of the above program ? Explain.

The name of the array is a constant pointer to the first element in the array. No value can
be assigned to the constant pointer within the program.

[Link] different ways of accessing the first , second and fifth


character of the array name_arr.
Eg: First character: name_arr[0], *name_arr

Second Character :

Fifth Character :

Two-dimensional Arrays

Consider the following declaration.

int a[8][5] ;

This is how a two dimensional array is defined.

We may define another variable, a_pt, as below


TATA CONSULTANCY SERVICES For Internal Use Only Page 35 of 55
UNIX & C Assignment_QZ Course Description Document

int **a_pt;

a_pt is a pointer to pointer an int. This means a_pt is a location which can hold the
address of address of an int.

Variable a_pt may also be viewed as an array of array of int. i.e., a two dimensional
array of int.

Given below is the pictorial representation of the array a.


0 1 2 3 4
0 a[0][0] a[0][1] a[0][2] a[0][3] a[0][4]
1 a[1][0]
2
3
4 a[4][2]
5
6
7 a[7][0] a[7][4]

We can assign a value, 10, to the element a[2][3] as follows :

a[2][3] = 10;

29. What are the other ways to do this ? Try to explain each one of
these representations.

e.g. *(a[2] + 3) = 10;

With the above definitions of variables a and a_pt, the following assignments are
valid.
**a_pt = a[0][2];
*a_pt = a[0];
*a_pt = a[5];
a_pt = a;

Since the array name ‘a’ is a constant pointer, the assignment a = a_pt is invalid.

Command line arguments

Command line arguments are arguments given, along with the program executable name,
at the command line. They are arguments passed from the programming environment
(operating system) to the function main().

30. What are the data types of the three command line arguments.
What do these three arguments represent ?

TATA CONSULTANCY SERVICES For Internal Use Only Page 36 of 55


UNIX & C Assignment_QZ Course Description Document
31. Are you familiar with the echo command in UNIX ? Write a program
which does the same using command line arguments .

32. What does the strcmp() function do ? Write your own function for
doing the comparison. Use arrays to store the strings and operations on
arrays.

e.g. If the inputs are “excel” and “word”, the output should be

word is larger than excel

This is because “word” is lexicographically larger than “excel”(“word” appears after


“excel” in the dictionary).

33. Write a second version of the above program using pointers and
command line arguments. Use pointer arithmetic instead of array indexes
to access each character of the strings.

Parameter passing

Consider the following function.


/* Program # 13 */
/* Program to illustrate parameter passing in functions in C */

#include <stdio.h>

void fixup(int nuts, int *fruit);

void main()
{
int acorns, apples;

acorns = 100;
apples = 150;
printf("The starting values are %d %d\n", acorns, apples);

/* Call function fixup by passing the value of acorns and


address of apples */
fixup(acorns, &apples);

printf("The ending values are %d %d\n", acorns, apples);


}

/* Function fixup takes nuts as an int value and fruit as a


pointer to an int */
void fixup(int nuts, int *fruit)

{
printf("The values are %d %d\n", nuts, *fruit);
nuts = 200;
*fruit = 250;
printf("The values are %d %d\n" ,nuts, *fruit);
}

TATA CONSULTANCY SERVICES For Internal Use Only Page 37 of 55


UNIX & C Assignment_QZ Course Description Document

34. What is the output of the above program ?

How will you explain the above?

In the above program, there are two variables defined in the main program, acorns and apples.
Notice that neither of these is defined as a pointer.

We assign values to both of these and print them out, then call the function named
fixup() taking both of these values along with us. The variable acorns is simply sent
to the function, but the address of the variable apples is sent to the function.

Now we have a problem. The two arguments are not the same, the second is a pointer to a
variable. We must somehow alert the function to the fact that it is supposed to receive an
integer variable and a pointer to an integer variable. This turns out to be very simple.
Notice that the parameter definitions in line
void fixup(int nuts, int *fruit) defines nuts as an integer, and fruit as a
pointer to an integer. The call in the main program therefore is now in agreement with the
function heading and the program interface will work just fine.

In the body of the function, we print the two values sent to the function, then modify
them and print the new values out. This should be perfectly clear to you by now.

The surprise occurs when we return to the main program and print out the two values
again. We will find that the value of acorns will be restored to the value it had prior to
the function call because the C language makes a copy of the item in question and takes
the copy to the called function, leaving the original intact. This is because ‘C’uses the
call by value method of parameter passing. In the case of the variable apples, we made
a copy of a pointer to the variable and took the copy of the pointer to the function. Since
we had a pointer to the original variable, even though the pointer was a local copy, it
pointed to the original variable and we could change the value of apples from within the
function. When we returned to the main program, we found a changed value in apples
when we printed it out.

Notice the prototype declaration in line 3,


void fixup(int nuts, int *fruits);.
TATA CONSULTANCY SERVICES For Internal Use Only Page 38 of 55
UNIX & C Assignment_QZ Course Description Document
This allows the compiler to check the type of both parameters when it gets to line
fixup(acorns, &apples); where the function is called.

By using a pointer in a function call, we can have access to the data in the function and change it in such a
way that when we return to the calling program, we have a changed value of the original variable. In this
example, there was no pointer in the main program because we simply sent the address to the function, but
in many programs you will use pointers in function calls. One of the places you will find need for pointers
in function calls will be when you request data input using standard input/output routines. Remember the
scanf() function where you send the address of the input variable as parameter.
[Link], try to explain the following.

/* Program # 14*/

#include <stdio.h>

main()
{
int num;

scanf(“%d”, &num);

printf(“\nInput = %d”, num);


}

Why does scanf use &num to read an integer into variable num where as
printf uses only num and not &num to print the value ?

[Link] a program containing function swap() which takes two integers from
the calling function, swaps their values and returns the swapped values to
the calling function.

Storage classes

Variables can belong to auto or static storage classes. Auto includes auto and register
variables and static includes static and extern variables.

Storage Classes tell about the place of storage, compile-time initialisation, lifetime and
scope of a variable.

auto int num_i;


register int num_ri;
static int num_si;
extern int num_ei;
char letter;

[Link] the storage class of each of the above variables.

[Link] at the following program. What is the output of the program ?

TATA CONSULTANCY SERVICES For Internal Use Only Page 39 of 55


UNIX & C Assignment_QZ Course Description Document

/* Program # 15 */

/* program to illustrate scope of a variable */


#include <stdio.h>

int i = 0;

main()
{
int i = 1;

printf(“First value of i is %d”, i);

{
int i = 2;

printf(“Second value of i is %d”, i);


{
i+= 1;
printf(“Third value of i is %d”, i);
}
printf(“Fourth value of i is %d”, i);

}
printf(“Fifth value of i is %d”, i);
}

[Link] is the output of the following program ?


/* Program # 16 */

#include <stdio.h>

int i = 1;
main()
{
int i, count;

i = reset ();

for (count = 1; count <= 3; count ++)


{
printf(“\ni = %d, count = %d”, i, count);

printf(“\nNext i = %d”, next(i));


printf(“\nLast i = %d”, last(i);
}
}

int reset()
{
return i;
}

int next(int j)
TATA CONSULTANCY SERVICES For Internal Use Only Page 40 of 55
UNIX & C Assignment_QZ Course Description Document
{
int i = 0;
return (j = i++);
}

int last(int j)
{
static int i = 10;

return (j = i--);
}

[Link] the use of each of the storage classes.

auto :

register :

static:

extern :

[Link] a program which takes in an input ‘n’ and generates n


fibonacci numbers (the series 0, 1, 1, 2, 3, 5, 8, 13…). Use a
function to generate fibonacci series and illustrate the use of static
variables.

Preprocessor commands

Preprocessor commands are commands, which are processed by the C-preprocessor


before the compiler compiles the code.
Two common pre-processor commands used are #include and #define.

[Link] are the other common pre-processor commands used ?

43. Which is the pre-processor command used for defining macros ?


How does the command work when a macro is called ?

44.#if….#elif…#endif does conditional compilation whereas


if….else… does conditional execution. Can you explain this ?

Structures and Unions

A structure is a collection of objects of same or different data types. Each member of the
structure is identified by an identifier.

TATA CONSULTANCY SERVICES For Internal Use Only Page 41 of 55


UNIX & C Assignment_QZ Course Description Document
[Link] the function main() of program #8 so that it takes and
stores employee number (integer), name and the number of items
made per hour by each of the 10 employees in a factory
department. Use a structure employee which stores the employee
id, name and total number of items made by each employee.
Compute and display the total number of items per day in the
factory.

[Link] at the following definitions

struct s {

int s1_i;
char s1_c;
float s1_f;
}s1;

union u {

int u1_i;
char u1_c;
float u1_f;
}u1;
What are the differences between the above variables, s1 and u1.

Self-referential structures and their applications

Self-referential structures are structures with pointers to themselves.


e.g.
typedef struct employee {
int empid_i;
char empname_ca[20];
int items_per_day_i;
struct employee *link_to_next;
}EMP;

EMP *prod_st;
[Link] is the data type of variable prod_st ? How will you access the
members empid_i, and empname_ca of prod_st ?

Look at the following problem statement.

Get the details – employee id, employee name and items made by the
employee per hour - of employees till the employee id is –999.

Here the number of employees can be varying from 0 to MAXINT or even beyond that.
So it will not be practical to have an array of structures .

In such situations where the number of array elements is dynamic we can create a linked
list of employee structures as given below.

/* Program # 17 */

/*Function to create a linked list of employee structures */


TATA CONSULTANCY SERVICES For Internal Use Only Page 42 of 55
UNIX & C Assignment_QZ Course Description Document
create_linkedlist()
{
EMP *first_st = NULL, *curr_st = NULL, *prev_st = NULL;
int empnum;

printf (“Give the Employee Id.\n”);


scanf(“%d”, &empnum);

while (empnum != -999)


{
curr_st = (EMP *)malloc(sizeof(EMP));
curr_st->empid_i = emp_num;
printf (“Give the Employee Name\n”);
scanf(“%s”, curr_st->empname_ca);
printf(“Give the items made per hour\n”);
scanf(“%d”, &curr_st-> items_per_day_i);
curr->link_to_next = NULL;

if (first_st ==NULL)
/* if first is NULL make the current node as first */
first_st = curr_st;
else
/* else make the previous link to current */
prev_st->link_to_next = curr_st;

/* set current node to previous */


prev_st = curr_st;

/* Take the next Employee number and continue */


printf (“\nGive the Employee Id.\n”);
scanf(“%d”, &empnum);

} /* end while*/

}/* end create() */

Understand the above function.


[Link] does the variable first point to after the linked list is
created ?

[Link] a program which uses the above function to create a linked


list of employees and another function to search for a given
employee number in the linked list you have already created and
delete the node

if the employee number is found in the list. Display the remaining


records.

[Link] the following program. Does it create a linked list at all ?


Why does this happen ?
/* Program # 18 */

typedef struct stud{


int id_i;
char name_ca[20];
int marks_i;
TATA CONSULTANCY SERVICES For Internal Use Only Page 43 of 55
UNIX & C Assignment_QZ Course Description Document
}STUD;

typedef struct student_node {


STUD student
struct student_node *link_to_next;
}NODE;

#include <stdio.h>

main()
{
void create_linkedlist(NODE *, STUD);
STUD new_stud;
NODE *head = NULL, *curr;

printf (“Enter the Student Id.\n”);


scanf(“%d”, &new_stud.id_i);

while (new_stud.id_i != -999)


{
printf (“Enter the Student Name\n”);
scanf(“%s”, new_stud.name_ca);
printf(“Enter the marks \n”);
scanf(“%d”, &new_stud.marks_i);

create_linkedlist(head, new_stud);

printf (“Enter the Student Id.\n”);


scanf(“%d”, &new_stud.id_i);
}
curr = head;
while (curr != NULL)
{
printf(“%d\n”, curr->student.id_i);
curr = curr->link_to_next;
}
}

/*Function to create a linked list of employee structures


in Last in First Out (LIFO) order */

create_linkedlist(NODE *first_st, STUD new_stud)


{

NODE *curr_st = NULL;

curr_st = (NODE *)malloc(sizeof(NODE));


curr_st->student.id_i = new_stud.id_i;
strcpy(new_stud.name_ca, curr_st->student.name_ca);
curr_st->student.marks_i = new_stud.marks_i;
curr_st->link_to_next = first_st;

first_st = curr_st;
return;

}/* end create() */

TATA CONSULTANCY SERVICES For Internal Use Only Page 44 of 55


UNIX & C Assignment_QZ Course Description Document
51. Now see the following corrected version of the above program.
Observe the changes. Execute this and understand its working. How will
you explain this ?

/* assume the same typedefs in the Program #18 for this corrected version
also */
/* Program #19 */
#include <stdio.h>

main()
{
void create_linkedlist(NODE **, STUD);
STUD new_stud;
NODE *head = NULL, *curr;

printf (“Enter the Student Id.\n”);


scanf(“%d”, &new_stud.id_i);

while (new_stud.id_i != -999)


{
printf (“Enter the Student Name\n”);
scanf(“%s”, new_stud.name_ca);
printf(“Enter the marks \n”);
scanf(“%d”, &new_stud.marks_i);

create_linkedlist(&head, new_stud);

printf (“Enter the Student Id.\n”);


scanf(“%d”, &new_stud.id_i);
}
curr = head;
while (curr != NULL)
{
printf(“%d\n”, curr->student.id_i);
curr = curr->link_to_next;
}
}

/*Function to create a linked list of employee structures


in Last in First Out (LIFO) order */

create_linkedlist(NODE **first_st, STUD new_stud)


{

NODE *curr_st = NULL;

curr_st = (NODE *)malloc(sizeof(NODE));


curr_st->student.id_i = new_stud.id_i;
strcpy(new_stud.name_ca, curr_st->student.name_ca);
curr_st->student.marks_i = new_stud.marks_i;
curr_st->link_to_next = *first_st;

*first_st = curr_st;
return;

}/* end create() */

TATA CONSULTANCY SERVICES For Internal Use Only Page 45 of 55


UNIX & C Assignment_QZ Course Description Document
[Link] there an alternative way to do this task by modifying the same
program ? If there is, give the steps to do this.

Files

Files provide permanent storage of data. C language provides features that help us handle
files in our programs. If you want to handle a file there should be at least one variable of
type FILE * defined in your program. FILE is a structure which is defined in the
header file, stdio.h. The first operation to be done on a file is to open the file.
[Link] the following statements
FILE *f_pt;

f_pt = fopen(“sample_file”, “r”);

What do the two parameters to fopen () denote ?

[Link] are the different opening modes of a file ? Explain each mode
in one line.

[Link] is the difference between “r+” and “w+” modes ?

[Link] will the file pointer be placed at the time of opening, if a file
is opened in the following modes ?

“r” :

“w” :

“a+” :

Note that in “a” or “a+” mode, writing into the file takes place only at the
end of the file.

57. Explain the following functions :

fclose(f_pt) :

feof(f_pt):

ferror(f_pt):

Reading and writing into the file can be done either using Formatted i/o functions or
unformatted i/o functions.

Formatted i/o functions are fscanf() and fprintf() which are similar to scanf()
and printf() functions.

TATA CONSULTANCY SERVICES For Internal Use Only Page 46 of 55


UNIX & C Assignment_QZ Course Description Document

58. Look at the following program.

/* Program # 20 */

#include <stdio.h>
main()
{

FILE * f_pt;
char inp_c;

f_pt = fopen(“sample”, “w”);


do
{
scanf(“%c”,&inp_c );
fprintf(f_pt,”%c”, inp_c);
} while( inp_c != ‘\n’);

fclose(f_pt);

f_pt = fopen(“sample”, “r”);


if (f_pt == NULL)
{
printf(“\nError in opening file sample”);
exit(1);
}

printf(“The contents of file sample :\n\n”);

fscanf(f_pt, “%c”, &inp_c);


while ( !feof(f_pt) && ( inp_c != ‘\n’ ) )
{

printf(“%c”, inp_c);
fscanf(f_pt, “%c”, &inp_c);
}
}

What does the above program do ?

59. Try to rewrite the above program by replacing fscanf() and


fprintf() by fread() and fwrite() respectively.

Note: The formatted i/o functions and unformatted i/o functions are incompatible to each
other. Hence a file written using fprintf() should be read only using fscanf() and
not fread(). Similarly a file written using fwrite() should be read only using
fread() and not fscanf().
rewind() and fseek() are functions used to position the file pointer.

TATA CONSULTANCY SERVICES For Internal Use Only Page 47 of 55


UNIX & C Assignment_QZ Course Description Document

60. Explain the function and usage of these two functions.

rewind() :

fseek() :

61. How will you use fseek() to rewind a file pointed by pointer f_pt ?

Function ftell() tells the position of file pointer in terms of number of bytes from the
beginning of the file.

62. Consider a file containing a few of the following the structure.


struct employee {
int empid_i;
char empname_ca[20];
int items_per_day_i;
};

How will you count the number of employee records in the file using
fseek()and ftell() after opening the file ? Assume that file pointer is f_pt.

63. Write a program to read some employee records of type struct


employee given above and store them in a file [Link]. The program
should continue taking input records till –999 is given as employee
number.

64. Write a program to sort the file [Link] created by the previous
program. Try to use linked list for sorting.

Pointers to functions

Examine the declaration given below for the most unusual pointer.

int (*func_pt)(char);

Here func_pt is a pointer to a function taking a char parameter and returning a int; That
means, the variable func_pt can point to any function taking a char parameter and
returning an int.

To understand more about function pointers, look at the following example.

/* Program # 21 */

/* Program illustrating pointers to function */

#include "stdio.h"

void print_stuff(float data_to_ignore);


void print_message(float list_this_data);
void print_float(float data_to_print);

void (*f_pt)(float);

TATA CONSULTANCY SERVICES For Internal Use Only Page 48 of 55


UNIX & C Assignment_QZ Course Description Document

void main()
{
float pi = 3.14159;
float two_pi = 2.0 * pi;

print_stuff(pi);
f_pt = print_stuff;
f_pt (pi);
f_pt = print_message;
f_pt (two_pi);
f_pt (13.0);
f_pt = print_float;
f_pt (pi);
print_float(pi);
}

void print_stuff(float data_to_ignore)


{
printf("This is the print stuff function.\n");
}

1. void print_message(float list_this_data)


2. {

3. printf("The data to be listed is %f\n", list_this_data);


4. }

5. void print_float(float data_to_print)


6. {
7. printf("The data to be printed is %f\n", data_to_print);
8. }

65. What is the output of the above program. ?

How will you explain the above ?

This program contains a pointer to a function, and illustrates how to use it.

Line 5 of this program declares f_pt as a pointer to a function and not to just any
function, it points to a function with a single formal parameter of type float. The function
must also return nothing because of the void before the pointer
definition. The parentheses are required around the pointer name as illustrated or the
system will think it is a prototype definition for a function that returns a pointer to void.
You will note the prototypes given in lines 2 through 4 that declare three functions that
use the same parameter and return type as the pointer. Since they are the same as the

TATA CONSULTANCY SERVICES For Internal Use Only Page 49 of 55


UNIX & C Assignment_QZ Course Description Document
pointer, the pointer can be used to refer to them as is illustrated in the executable part of
the program.
Line 10 contains a call to the print_stuff() function, and line 11 assigns the value of
print_stuff() to f_pt. Because the name of a function is defined as a pointer to that
function, its name can be assigned to a function pointer variable. You will recall that the
name of an array is actually a pointer constant to the first element of the array. In like
manner, a function name is actually a pointer constant which is pointing to the function
itself.
The pointer is successively assigned the address of each of the three functions and each is
called once or twice as an illustration of how a pointer to a function can be
used.
A function pointer can be passed to another function as a parameter and can be used
within the function to call the function which is pointed to. You are not permitted to
increment or add a constant to a function pointer, it can only be assigned the value of a
function with the same parameters and return with which it was initially declared. It may
take you a little time to appreciate the value of this construct, but when you do
understand it, you will see the flexibility built into the C programming language.

A pointer to a function is not used very often but it is a very powerful construct when
needed.

Appendix B
More I/O Functions

sscanf()

int sscanf(char *s, const char *format, ...) is equivalent to


scanf(...) except that the input is taken from the string s instead of the standard input
stream.

sprintf()
int sprintf ((char *s, const char *format,...) is same as
printf(...) except that the output is written into the string s terminated with '\0'. s
must be big enough to hold the result. The function returns an integer which is equal to
he number of characters written into the string, excluding '\0'.
This function can be used for formatting any arbitrary input.

TATA CONSULTANCY SERVICES For Internal Use Only Page 50 of 55


UNIX & C Assignment_QZ Course Description Document
[Link] does the following program do ?

/* Program 1*/

/* Program illustrating the working of sscanf()and sprintf()


functions */

void main( )
{
int numbers[5], result[5], index;
char line[80];

numbers[0] = 74;
numbers[1] = 18;
numbers[2] = 33;
numbers[3] = 30;
numbers[4] = 97;

sprintf(line,"%d %d %d %d %d\n" ,numbers[0],


numbers[1], numbers[2], numbers[3], numbers[4]);
printf("%s",line);

sscanf(line,"%d %d %d %d %d", &result[4], &result[3],


(result+2), (result+1), result);

for (index = 0; index < 5; index++)


printf("The final result is %d\n", result[index]);
}

It may look silly to read input data from within the computer but it does have a real
purpose. It is possible to read data from an input device using any of the standard
functions and then do a format conversion in memory. You could read in a line of data,
look at a few significant characters, then use these formatted input routines to reduce the
line of data to internal representation. That would certainly be better than writing your
own data formatting routines!

[Link] a program using the sscanf function to convert a date in the


form of "dd/mm/yy" into the respective integers representing day,
month and year and print the integer values.

vprintf() and vscanf()


The variable argument list in printf() (remember that printf() can print any
number of values given as arguments) is replaced by single argument in vprintf(). The
single argument has to be initialised by calling the va_start macro. Similarly there is
the vscanf() function also.

More on Bit-wise Operators


C provides six operators for bit manipulation which are extensively used in low level
programming, encrypting/decrypting programs and programs implementing graphics.
They are applied only to integral operands - char, int, short int and long int
(signed or unsigned) . These operators are as follows.
TATA CONSULTANCY SERVICES For Internal Use Only Page 51 of 55
UNIX & C Assignment_QZ Course Description Document

Operator Meaning
~ One's complement
(bitwise negation)
& AND
| OR
^ Exclusive OR
(XOR)
>> Shift right
<< Shift left

One's Complement (~)

The bitwise negation ~ (or bit flip) requires one operand. i.e., ~ is a unary operator. The
result of the operation is the one's complement of the operand. The ~ operator changes all
1 bits to 0 and all 0 bits to 1.

For example a and the negation of a would be represented as:

a = 0000 0000 0000 0001


~a = 1111 1111 1111 1110

A negative integer number( -a) can be represented with help of negation:

~a+1

AND (&)

This can be used to mask some set of bits in a given bit pattern.

OR (|)
Used to turn on some bits in a given bit pattern . For eg. x | SET_ON where SET_ON is
a constant, sets to 1 in x, the bits which are set to one in SET_ON

XOR (^)

This operator sets a one in each bit where bits in operands are different and zero where
they are the same.

The properties of the three operators, &, | and ^ are illustrated below, when applied to
the initial values of 'a' and 'b':

a = 0011 a = 0011 a = 0011


b = 0101 b = 0101 b = 0101
----------- ----------- -----------
a&b = 0001 a|b = 0111 a^b = 0110

Examples for masking and setting on bits


TATA CONSULTANCY SERVICES For Internal Use Only Page 52 of 55
UNIX & C Assignment_QZ Course Description Document

Suppose that the bit string is 00000101 (rightmost bit is bit 0 and the leftmost bit is bit 7)

Turn OFF bit 2:


Original bit string
00000101
mask
11111011
Result of &
00000001
AND (&) original string with "mask" ;

note there are 1's everywhere except pos. 2 and bit 2 has been turned OFF

Turn ON bit 4:
Original bit string
00000101
mask
00010000
Result of |
00010101
OR (|) original stringwith "mask";

0's everywhere except the desired position

and bit 4 has been turned ON

To set the most rightmost bit of an integer variable d to zero it's enough to perform the
following operations:

~1&d (inversion of one, bitwise AND of d)

Let's assume that d=33(decimal). The table below shows the evolution of data change in
this process:

d = 0000 0000 0010 0001


1 = 0000 0000 0000 0001
~1 = 1111 1111 1111 1110
~1 & d = 0000 0000 0010 0000

Using ~1 & d instead of 1111 1111 1111 1110 & d is better since the former is
independent of word length where as the later assumes that d is a 16-bit quantity. This
portability involves no extra cost since ~1 is a constant expression which can be
evaluated at compile time.

[Link] does the following program do ?

/* Program #2 */
#include <stdio.h>
main()
TATA CONSULTANCY SERVICES For Internal Use Only Page 53 of 55
UNIX & C Assignment_QZ Course Description Document
{
int a. b;

scanf(“%d %d”, &a, &b);


a = a^b;
b = a^b;
a = a^b;

printf(“%d %d \n”, a, b);

Left Shift (<<) and Right Shift (>>)


The operation e1 << e2 shifts the left operand e1 to the left by the number of bits
specified by the right operand e2. The vacated bits in the left operand are 0-filled (logical
fill). There is NO wrap around of bits.

The right shift operation e1>>e2 is performed in the same way with several exceptions
for some CPU platforms. The right shift of integers in those CPUs can be arithmetic shift,
i.e. the vacated bits from the left will be filled by the value of a "sign" bit (the first bit
from the left). Nevertheless, it is guaranteed that the right shift of unsigned integers is a
logical shift and the vacated bits from the left are 0 filled.

For eg., x << 2 shifts the value of x by 2 positions filling the vacated bits with zero.
This is equivalent to multiplying x by 4. Similarly, shifting x to right by 2 bits is
equivalent to dividing x by 4 if the shift is a logical one (vacated bits from the left are 0
filled).

Note: Shifting is much faster than actual multiplication (*) or division (/) by 2. So if you
want fast multiplications or division by 2, use shifts.

The type of the result of these operations is defined by the type of the left operand. The
result of an operation can be undefined in the following situations:
6. the right operand is a negative;
7. the bit size of the right operator is equal to or larger than the one of the object.

[Link] is a function which gets n bits from position p of an input x.


Conventionally bits are numbered starting from 0 at the rightmost
position.

/* Program #3 */

/* get n bits from position p */


unsigned getbits (unsigned x, int p, int n)
{
return (x>> (p+1 - n)) & ~(~0 << n);

Understand the working of this function.

TATA CONSULTANCY SERVICES For Internal Use Only Page 54 of 55


UNIX & C Assignment_QZ Course Description Document
Write a similar function setbits(x, p, n, y) to set n bits from
position p of the input x equivalent to the rightmost n bits of y leaving
others unchanged.

TATA CONSULTANCY SERVICES For Internal Use Only Page 55 of 55

You might also like