UNIX & C Course Overview and Commands
UNIX & C Course Overview and Commands
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?
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?
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.
mkdir
To create a directory.
cd
Change Directory
rmdir
ls
10. What are the different fields in the long listing of the directory?
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
ln
mv
Move the contents of a file onto another. (This is like rename in DOS).
19. How will you copy a directory structure dir1 to dir2 ? (with all the
subdirectories)
rm
chmod
23. Explain about each of the options along with chmod, namely, + - = etc. Try
out all these and compare.
who
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
27. How to get only the options and arguments of a command excluding the
descriptive help?
du
28. Find the space occupied ( in Bytes) by the /home directory including all its
subdirectories.
df
clear
cat
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
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
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.
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?
42. What is the command for printing the calendar of the current month?
bc
Basic Calculator
wc
45. What is the command for printing the number of lines in the ‘passwd’ file?
sort
46. What are the commands used to sort some information in the reverse order
and in the numerical order?
uniq
48. What do the commands uniq –c, uniq –d and uniq –u do?
find
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.
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.
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?
61. Connect the two commands cat part1 part2 > total and lpr total using tee.
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:
64. What is the command to introduce a new line above the first line in a file?
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?
REGULAR EXPRESSIONS
‘*’ character is used both as a shell wild card character and in regular
expressions. What is the difference in the interpretations?
grep, sed
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?
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.
83. What is the command for bringing the 3rd background job to the foreground?
And how will you put it back in the background?
ps
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?
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
89. Give an example of making a variable available to all the processes using
export. Is it truly becoming available to all?
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?
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.
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?
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.
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. )
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.
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?
etc...
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.
etc...
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
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
${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
cd $SPOOL
$?
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.
# 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...
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?
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
etc...
#!/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`
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.
main : printf :
scanf : for :
char : stdio.h :
#include : struct :
“a” : EOF :
‘a’ : while :
NULL : switch :
#define : typedef :
if : FILE :
{} : ():
‘‘: ; :
3. Is there any component /symbol in your program which does not belong to
any of these categories ? If yes, mention the symbol(s).
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 ?
#include <stdio.h>
main()
{
int a = 1, b = 2, c =3;
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*/
main()
{
int integer, temp, count = 0, bit, word;
unsigned int mask;
temp = integer;
mask = 1;
word = 8 * sizeof(int);
#include <stdio.h>
main()
{
unsigned int 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 :
#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
}
/* Program # 5*/
#include <stdio.h>
main()
{ int a, b;
scanf(“%d”, &a); printf(“\n%d”, a * 8);
}
/* Program # 6 */
main ()
{
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.)
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.
main ()
{
count = 0;
valid_int = 1;
valid_int = 0;
/* 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 */
main ()
{
items_per_hour = get_valid_int(input);
int count = 0;
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.
Recursion
/* Program # 9*/
#include <stdio.h>
void myprint(int);
main()
{
myprint(0);
}
void myprint(int i)
{
if (i<5)
{
myprint(++i);
printf("%d ", i);
}
}
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] 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.
Pointers
#include <stdio.h>
void main()
{
/* declare an integer variable index and two pointers pt1 and pt2. pt1
and pt2 are pointers to int */
24. How does the output of the above program look ? Try to explain the
behaviour of the program.
/* Program # 11 */
#include <stdio.h>
main()
{
int *pt1;
Tips to remember
Arrays and Pointers can be synonymously used. Look at the following program.
/* Program # 12 */
#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);
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.
Second Character :
Fifth Character :
Two-dimensional Arrays
int a[8][5] ;
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.
a[2][3] = 10;
29. What are the other ways to do this ? Try to explain each one of
these representations.
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 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 ?
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
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
#include <stdio.h>
void main()
{
int acorns, apples;
acorns = 100;
apples = 150;
printf("The starting values are %d %d\n", acorns, apples);
{
printf("The values are %d %d\n", nuts, *fruit);
nuts = 200;
*fruit = 250;
printf("The values are %d %d\n" ,nuts, *fruit);
}
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.
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);
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.
/* Program # 15 */
int i = 0;
main()
{
int i = 1;
{
int i = 2;
}
printf(“Fifth value of i is %d”, i);
}
#include <stdio.h>
int i = 1;
main()
{
int i, count;
i = reset ();
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--);
}
auto :
register :
static:
extern :
Preprocessor commands
A structure is a collection of objects of same or different data types. Each member of the
structure is identified by an identifier.
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.
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 ?
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 */
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;
} /* end while*/
#include <stdio.h>
main()
{
void create_linkedlist(NODE *, STUD);
STUD new_stud;
NODE *head = NULL, *curr;
create_linkedlist(head, new_stud);
first_st = curr_st;
return;
/* 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;
create_linkedlist(&head, new_stud);
*first_st = curr_st;
return;
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;
[Link] are the different opening modes of a file ? Explain each mode
in one line.
[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.
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.
/* Program # 20 */
#include <stdio.h>
main()
{
FILE * f_pt;
char inp_c;
fclose(f_pt);
printf(“%c”, inp_c);
fscanf(f_pt, “%c”, &inp_c);
}
}
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.
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.
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.
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.
/* Program # 21 */
#include "stdio.h"
void (*f_pt)(float);
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);
}
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
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()
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.
/* Program 1*/
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;
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!
Operator Meaning
~ One's complement
(bitwise negation)
& AND
| OR
^ Exclusive OR
(XOR)
>> Shift right
<< Shift left
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.
~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':
Suppose that the bit string is 00000101 (rightmost bit is bit 0 and the leftmost bit is bit 7)
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";
To set the most rightmost bit of an integer variable d to zero it's enough to perform the
following operations:
Let's assume that d=33(decimal). The table below shows the evolution of data change in
this process:
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.
/* 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;
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.
/* Program #3 */