Sunteți pe pagina 1din 51

1

FREE OPEN SOURCE SOFTWARE(FOSS) Lab


Manual.

R13 Syllabus – JNTUK

Faculty
Prepared by V Prasad,
Associate Professor , Dept of CSE.

Raghu Institute of Technology


Approved by AICTE(New Delhi) , Affiliated to JNTU-K(Kakinada , Andhra Pradesh),
Dakamarri(V), Bheemunipatnam (M), Visakhapatnam District, Andhra Pradesh, India.
Tel No: +91 8922 248003, 248013. Fax no: +91 8922 248013. Website: www.raghuinstech.com

Raghu Institute of Technology II Year


II Sem Computers
2

LAB OBJECTIVE

 This is the BASIC Language at engineering level which gives a foundation for
the upcoming period.

 Logical thinking is given for solving the given problem.


 The learned c language can help a student at industry level.
 Gives enough knowledge in C basics.
 More idea on Algorithms & Flowcharts.
 Usage of Algorithms & Flowcharts.
 Difference between process and program can understood.
 Difference between Algorithm and Pseudocode .
 Several programs in C for perfection in syntactic & semantic representation.
 Working ability can be increases on VI Editor and EMACS editor in FEDORA /
SUSE linux.
 Various header file usages and the methodologies used for compiling them is
known
 Number Systems like BCD , Octal , Hexadecimal can be viewed.
 Clear deviations in Machine Language , Assembly Language , Application
languages is done.
 Interesting topics like Arrays , Pointers , Functions, Structures & Unions can be
implemented.
 Discussion a variety of current issues related to using C in educational settings.
 Discussion on advantages and disadvantages in C .
 Used Inbuilt VI Editor from FEDORA/ SUSI Linux and executed all programs
on it.
 Came to know how secure the LINUX operating system is.
 Came to know the difference between programs and files.
 Known the difference between compile time execution and run time execution.
 Completion of my lab taught me saying that C is an Ocean and there is lot more
to work on.( like graphics , multimedia , dynamic data collection …)

RAGHU INSTITUTE OF TECHNOLOGY


FREE OPEN SOURCE SOFTWARE (FOSS) LAB

Year & Programme : II Year, 2013-14

Raghu Institute of Technology II Year


II Sem Computers
3

Branch / Semester : CSE / II Semester

Experiment ∷1

Session-1
a)Log into the system
Output : Login

b)Use vi editor to create a file called myfile.txt which contains some text.
Output : vi mytable
c)correct typing errors during creation.
Output : Practice vi editor commands\

d)Save the file


Output : :wq +Enter

e)logout of the system


Output : logout

To Enter VI Editor:

To Start vi

To use vi on a file, type in vi filename. If the file named filename exists, then the
first page (or screen) of the file will be displayed; if the file does not exist, then
an empty file and screen are created into which you may enter text.

 vi filename edit filename starting at line 1


 vi –r filename recover filename that was being edited when system
crashed

To Exit vi

Usually the new or modified file is saved when you leave vi. However, it is also
possible to quit vi without saving the file.
Note: The cursor moves to bottom of screen whenever a colon (:) is typed. This
type of command is completed by hitting the <Return> (or <Enter>) key.

Raghu Institute of Technology II Year


II Sem Computers
4

:x quit vi, writing out modified file to file named in original invocation
:wq quit vi, writing out modified file to file named in original invocation
:q quit (or exit) vi
:q! quit vi even though latest changes have not been saved for this vi call

Session-2
a)Log into the system
b)open the file created in session 1
c)Add some text
d)Change some text
e)Delete some text
f)Save the Changes
Output : Practice the commands in Vi editor g)Logout of the system

Note… Make Use of following commands

Inserting or Adding Text

The following commands allow you to insert and add text. Each of these commands
puts the vi editor into insert mode; thus, the <Esc> key must be pressed to terminate the
entry of text and to put the vi editor back into command mode.

* i insert text before cursor, until <Esc> hit


I insert text at beginning of current line, until <Esc> hit
* a append text after cursor, until <Esc> hit
A append text to end of current line, until <Esc> hit
open and put text in a new line below current line, until <Esc>
* o hit
open and put text in a new line above current line, until <Esc>
* O hit

Changing Text

The following commands allow you to modify text.


*r replace single character under cursor (no <Esc> needed)
*R replace characters, starting with current cursor position, until <Esc> hit
change the current word with new text,
cw
starting with the character under cursor, until <Esc> hit
change N words beginning with character under cursor, until <Esc> hit;
cN e.g., c5w changes 5 words
w
C change (replace) the characters in the current line, until <Esc> hit

Raghu Institute of Technology II Year


II Sem Computers
5

cc change (replace) the entire current line, stopping when <Esc> is hit
change (replace) the next N lines, starting with the current
line, Ncc or cNc stopping when <Esc> is hit

Deleting Text

The following commands allow you to delete text.


*x delete single character under cursor
Nx delete N characters, starting with character under cursor delete the
dw single word beginning with character under cursor
dNw delete N words beginning with character under cursor; e.g., d5w
deletes 5 words
D delete the remainder of the line, starting with current cursor position
* dd delete entire current line

Ndd or dNd delete N lines, beginning with the current line;


e.g., 5dd deletes 5 lines

Raghu Institute of Technology II Year


II Sem Computers
Experiment ∷ 2

a)Log into the system


b)Use the cat command to create a file containing the following data. Call it mytable
use tabs to separate the fields.

1425 Ravi 15.65


4320 Ramu 26.27
6830 Sita 36.15
1450 Raju 21.86

Output
cat > mytable
1425 Ravi 15.65
4320 Ramu 26.27
6830 Sita 36.15
1450 Raju 21.86

c)Use the cat command to display the file,


mytable.
Output : $cat mytable
1425 Ravi 15.65
4320 Ramu 26.27
6830 Sita 36.15
1450 Raju 21.86

d) Use the vi command to correct any errors in the file mytable.,


Output : Verify the file with Vi editor Commands

e) Use the sort command to sort the file mytable according to the first field. Call
the sorted file my table
( same name)
Output : $sort +1 mytable > mytable

f) Print the file mytable


Output : cat mytable
1425 Ravi 15.65
1450 Raju 21.86
4320 Ramu 26.27
6830 Sita 36.15

g) Use the cut and paste commands to swap fields 2 and 3 of mytable. Call it my
table (same name)
Output : $cut -f1 >
mytab1 $ cut –f 2 >
mytab 2 $cut –f 3 >
my tab3
$paste mytab3 mytab2 >
mytab4 $paste mytab1
mytab4 > mytable

h)Print the new file, mytable


Output : $ cat mytable
1425 15.65 Ravi
1450 21.86 Raju
4320 26.27 Ramu
6830 36.15 Sita

i)Logout of the system.

Cat:----

cat to display a text file or to concatenate files


displays contents of file1 on the screen (or window)
cat file1 without any screen breaks.

displays contents of file1 followed by file2 on the


cat file1 file2
screen (or window) without any screen breaks.
cat file1 file2 > file3 creates file3 containing file1 followed by file2

Sort :----

The "sort" command sorts information piped into it. There are several options that
let you sort information in a variety of ways.
ps -ef | sort

The most important options in Sort :

The following list describes the options and their arguments that may be used to
control how sort functions.

 Forces sort to read from the standard input. Useful for reading from
pipes and files simultaneously.
 -c Verifies that the input is sorted according to the other options
specified on the command line. If the input is sorted correctly then
no output is provided. If the input is not sorted then sort informs
you of the situation. The message resembles this.
 sort: disorder: This line not in sorted order.
 -m Merges the sorted input. sort assumes the input is already
sorted. sort normally merges input as it sorts. This option informs
sort that the input is already sorted, thus sort runs much faster.
 -o output Sends the output to file output instead of the standard
output. The output file may be the same name as one of the input
files.
 -u Suppress all but one occurrence of matching keys. Normally, the
entire line is the key. If field or character keys are specified, then
the suppressing is done based on the keys.
 -y kmem Use kmem kilobytes of main memory to initially start the
sorting. If more memory is needed, sort automatically requests it
from the operating system.
 -z recsz Specifies the record size used to store each line. Normally the
recsz is set to the longest line read during the sort phase. If the -c or
-m options are specified, the sort phase is not performed and thus the
record size defaults to a system size.

The amount of memory allocated for the sort impacts the speed of the sort
significantly. If no kmem is specified, sort starts with the default amount of
memory (usually 32K). The maximum (usually 1 Megabyte) amount of memory
may be allocated if needed.
If 0 is specified for kmem, the minimum (usually 16K) amount of memory is
allocated.
If this default size is not large enough, sort may abort during the merge phase. To
alleviate this problem you can specify a recsz that will allow the merge phase to run
without aborting. Experiment ∷ 3
Session1:
a)Login to the system
b)Use the appropriate command to determine your login shell

Output : $echo $SHELL


sh
c)Use the /etc/passwd file to verify the result of step b.

Output : $cat /etc/passwd

d)Use the who command and redirect the result to a file called myfile1. Use the
more command to see the contents of myfile1.

Output : $who > myfile1 | more

User1 pts/0 Apr 23 10:43


User2 pts/1 May 6 18:19
e)Use the date and who commands in sequence (in one line) such that the output
of date will display on the screen and the output of who will be redirected to a
file called myfile2. Use the more command to check the contents of myfile2.

Output : $ date ; who > myfile2

Fri April 9 16:47:32 IST 2013


Cat myfile2 :

User3 pts/2 Apr 25 10:43


User4 pts/3 May 8 18:19
Who :---

The "who" command lets you display the users that are currently logged into
your Unix computer system.

who
This is the basic who command with no command-line arguments. It shows the names of
users that are currently logged in, and may also show the terminal they're logged in on,
and the time they logged in.
who | more

In this example the output of the who command is piped into the more command. This
is useful when there are a lot of users logged into your computer system, and part of the
output of the who command scrolls off the screen. See the more command for more
examples.

who -a

The -a argument lists all available output of the who command for each user.

Piping:---

To connect the output of the one command directly to the input of the other command.
This is exactly what pipes do. The symbol for a pipe is the vertical bar |
For example, typing

% who | sort

will give the same result as above, but quicker and cleaner.

To find out how many users are logged on, type


% who | wc -lSession 2:

Input File : file1.dat :


Unix is Multiuser OS
Unix was developed by Brian Kernighan and KenThomson

a)Write a sed command that deletes the first character in each line in a file.

Output:
sed 's/^./ /‟ file1.dat
nix is Multiuser OS
nix was developed by Brian Kernighan and KenThomson

b)Write a sed command that deletes the last character in each line in a file.
Output:

sed '$s/.$//' file1.dat


Unix is Multiuser O
Unix was developed by Brian Kernighan and KenThomso

c)Write a sed command that swaps the first and second words in each line in a
file.
Output:
sed -e 's/\([^ ]\+\) *\([^ ]\+\)/\2 \1/'
sed 's/\([a-z]*\) \([a-z]*\)/\2 \1/' (Modified & working)

(Substrings enclosed with "\(" and "\)" can be referenced with "\n" (n is a digit from 1
to 9) )

Ref : http://www.grymoire.com/Unix/Sed.html#uh-0
Experiment∷4

a)Pipe your /etc/passwd file to awk, and print out the home directory of each user.

Output:
cat /etc/passwd | awk „ { print $7}‟

b)Develop an interactive grep script that asks for a word and a file name and then tells
how many lines contain that word.

Output:

echo “Enter a word”


read word
echo “Enter the filename”
read file
nol=grep -c $word $file
echo “ $nol times $word present in the $file”

c)Part using awk

Output:

echo “Enter a word”


read word
echo “Enter the filename”
read file
nol=awk „/$word/ { print NR }‟ Infile
echo “ $nol times $word present in the $file”

Grep: ---grep is one of many standard UNIX utilities. It searches files for
specified words or patterns. First clear the screen, then type
% grep science science.txt
As you can see, grep has printed out each line containg the word science.
Or has it ????
Try typing
% grep Science science.txt

The grep command is case sensitive; it distinguishes between Science and science.
To ignore upper/lower case distinctions, use the -i option, i.e. type
% grep -i science science.txt
To search for a phrase or pattern, you must enclose it in single quotes (the
apostrophe symbol). For example to search for spinning top, type
% grep -i 'spinning top' science.txt

Some of the other options of grep are:

-v display those lines that do NOT match


-n precede each matching line with the line
number -c print only the total count of matched
lines

Try some of them and see the different results. Don't forget, you can use more than
one option at a time. For example, the number of lines without the words science
or Science is

% grep -ivc science science.txt

Ref : http://www.grymoire.com/Unix/Awk.html
Experiment∷ 5

a)Write a shell script that takes a command –line argument and reports on whether it is
directory, a file, or something else.

Output:
echo " enter
file" read str
if test -f $str
then echo "file exists n it is an ordinary
file" elif test -d $str
then echo "directory
file" else
echo "not
exists" fi
if test -c $str
then echo "character device
files" fi

b)Write a shell script that accepts one or more file name as arguments and converts all of
them to uppercase, provided they exist in the current directory.

Output:
# get filename
echo -n "Enter File Name :
" read fileName

# make sure file exits for reading


if [ ! -f $fileName ]
then
echo "Filename $fileName does not
exists" exit 1
fi

# convert uppercase to lowercase using tr


command tr '[A-Z]' '[a-z]' < $fileName

c)Write a shell script that determines the period for which a specified user is working on
the system.

Output:

echo “enter the login of the


user” read name
logindetails=`who|grep –w “$name” | grep
“tty” if [ $? –ne 0 ]
then
echo “$name has not logged in
yet” exit
fi
loginhours=`echo “$logindetails” | cut –c 26,27`
loginminuts=`echo “$logindetails” | cut –c 29-30`
hoursnow=‟date | cut –c 12,13`
minnow =`date | cut –c 15,16`
hour=`expr $loginhours - $hoursnow`
min=`expr $loginminuts - $minnow`
echo “ $name is working since
$hour Hrs - $min Minuts”
Experiment∷ 6

a)Write a shell script that accepts a file name starting and ending line numbers as
arguments and displays all the lines between the given line numbers.

Output:

If [ $# -ne 3 ]
then
echo “chech the arguments once”
lastline=‟wc –l < $1‟
if [ $2 –lt $lastline –a $3 -le $lastline ]
then
nline=‟expr $3 -$2 + 1‟
echo “‟tail +$2 $1 | head -
$nline‟” else
echo “invalid range specification”
fi
fi

b) Write a shell script that deletes all lines containing a specified word in one or more
files supplied as arguments to it.

Output:
if [ $# -lt 1]
then
echo “ Chech the arguments once”
exit
fi
echo “Enter a
word” read word
for file in
$* do
grep –iv “$word” $file | tee 1> /dev/null
done
echo “ lines containing given word are deleted”
Experiment ∷ 7
a)Write a shell script that computes the gross salary of a employee according to the
following rules:
i)If basic salary is < 1500 then HRA =10% of the basic and DA =90% of the basic.
ii)If basic salary is >=1500 then HRA =Rs500 and DA=98% of the basic
The basic salary is entered interactively through the key board.

Output:
echo enter basic salary
read sal
a=0.1
b=0.8
echo $a
echo "hra is"
hra=`echo 0.1 \* $sal|
bc` echo da is
da=`echo 0.8\*$sal|bc`
gsal=‟expr $hra + $da +
$sal‟ echo $gsal

b)Write a shell script that accepts two integers as its arguments and computers the value
of first number raised to the power of the second number.

Output:

If [ $# -ne 2]
then
echo “chech the number of arguments”
count=1
result=1
if [ $2 –ge 0 ]
then
while [ $count –le $2 ]
do
result=`expr $result \* $1`
count=`expr $count + 1`
done
fi
fiExperiment ∷ 8

a)Write an interactive file-handling shell program. Let it offer the user the choice of
copying, removing, renaming, or linking files. Once the user has made a choice, have the
program ask the user for the necessary information, such as the file name, new name and
so on.
b)Write shell script that takes a login name as command – line argument and reports
when that person logs in

Output:
#Shell script that takes loginname as command line arg and reports when that person logs
in.
if [ $# -lt 1 ]
then
echo improper usage
echo correct usage is: $0 username
exit
fi
logname=$
1 while true
do
who|grep "$logname">/dev/null
if [ $? = 0 ]
then
echo $logname has logged in
echo "$logname">>sh01log.txt
date >>sh01log.txt
echo "Hi" > mesg.txt
echo "$logname" >> mesg.txt
echo "Have a Good Day" >>
mesg.txt mail "$logname" < mesg.txt
exit
else
sleep 60 fi done

c)Write a shell script which receives two file names as arguments. It should check
whether the two file contents are same or not. If they are same then second file should
be deleted.

Sol:
echo “enter first file name”
read file1
echo “ enter second file name”
read file2
cmp file1 file2 > file3

if [ -z $file1 ] rm file2
fi
echo “duplicate file deleted successfully”
Experiment ∷ 9
a)Write a shell script that displays a list of all the files in the current directory to which
the user has read, write and execute permissions.

Output:

ls –l | grep “^.rwx” | cut –f 9

b)Develop an interactive script that ask for a word and a file name and then tells how
many times that word occurred in the file.
c)Write a shell script to perform the following string operations:
i)To extract a sub-string from a given string.
ii)To find the length of a given string.

Note: Make use of Following Link to know about Shell Programming

Ref : http://www.freeos.com/guides/lsst/ch02.html
Experiment ∷ 10
Write a C program that takes one or more file or directory names as command line input and
reports the following information on the file:
i)File type
ii)Number of links
iii)Read, write and execute permissions
iv)Time of last access

Output:

#include<stdio.h>
#include<unistd.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h> void
main()
{ int fd; struct stat
buf;
fd=open("f5.txt",O_RDONLY|O_CREAT,600); if(fd!
=-1)
{ if(fstat(fd,&buf)==0)
{ printf("mode of fileis %u",buf.st_mode); printf("\n
size of the file is %u",buf.st_size); printf("\n device
name %u",buf.st_dev); printf("\n inode of file is
%u",buf.st_ino); printf("\n no. of links are
%u",buf.st_nlink); printf("\n owner oof a file is
%u",buf.st_uid); printf("\n no.of blocks is
%u",buf.st_blocks); printf("\n group owner is
%u",buf.st_gid);
printf("\n blocks size of the file is %u",buf.st_blksize);
printf("\n time of last modifiedis %u",buf.st_ctime);

}
else
printf("error in fstat() syscall");
}
else
printf("error in open() sys call");
}

Stat : --

NAME
stat - get file statusSYNOPSIS

#include < sys/stat.h>


int stat(const char *restrict path, struct stat *restrict buf);

DESCRIPTION

The stat() function shall obtain information about the named file and write it to the area
pointed to by the buf argument. The path argument points to a pathname naming a file. Read,
write, or execute permission of the named file is not required. An implementation that
provides additional or alternate file access control mechanisms may, under implementation-
defined conditions, cause stat() to fail. In particular, the system may deny the existence of the
file specified by path.

If the named file is a symbolic link, the stat() function shall continue pathname
resolution using the contents of the symbolic link, and shall return information pertaining
to the resulting file if the file exists.

The buf argument is a pointer to a stat structure, as defined in the <sys/stat.h> header, into
which information is placed concerning the file.

The stat() function shall update any time-related fields (as described in the Base Definitions
volume of IEEE Std 1003.1-2001, Section 4.7, File Times Update), before writing into the stat
structure.

Unless otherwise specified, the structure members st_mode, st_ino, st_dev, st_uid, st_gid,
st_atime, st_ctime, and st_mtime shall have meaningful values for all file types defined in this
volume of IEEE Std 1003.1-2001. The value of the member st_nlink shall be set to the
number of links to the file.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set
to indicate the error

<sys/stat.h> : ---

The stat structure shall contain at least the following members:

dev_t st_dev Device ID of device containing file.


ino_t st_ino File serial number.
mode_t st_mode Mode of file (see below).
nlink_t st_nlink Number of hard links to the file.
uid_t st_uid User ID of file.
gid_t st_gid Group ID of file.
dev_t st_rdev Device ID (if file is character or block
special).
off_t st_size For regular files, the file size in bytes.
For symbolic links, the length in bytes of the pathname contained in the symbolic link.
For a shared memory object, the length in bytes.
For a typed memory object, the length in bytes.
For other file types, the use of this field is unspecified.
time_t st_atime Time of last access.
time_t st_mtime Time of last data modification.
time_t st_ctime Time of last status change.
blksize_t st_blksize A file system-specific preferred I/O block
size for this object. In some file system types, this may vary from
file to file.

Number of blocks allocated for this object.


Experiment ∷ 11

Write C programs that simulate the following unix commands:


a)mv
Output:

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.>
void main()
{
int fd1,fd2;
char buf[60];
char *p="/f2";
fd1=open("f2",O_RDWR);
fd2=open("f6",O_RDWR);
read(fd1,buf,sizeof(buf));
write(fd2,buf,sizeof(buf));
remove(p);
}

b)cp

Output:

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h
> void main()
{
int fd1,fd2;
char buf[60];
fd1=open("f2",O_RDWR);
fd2=open("f6",O_RDWR);
read(fd1,buf,sizeof(buf));
write(fd2,buf,sizeof(buf));
close(fd1);
close(fd2);
}
System calls for File Processing :----

FreeBSD (4.4) has six file-related system calls. The following table briefly describe the
function of each.

System calls Function


open open an existing file or create a new file
read Read data from a file
write Write data to a file
lseek Move the read/write pointer to the specified location
close Close an open file
unlink Delete a file
chmod Change the file protection attributes
stat Read file information from inodes

Files to be included for file-related system calls.

#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/stat.h>

Open files

The open system call can be used to open an existing file or to create a new file if it
does not exist already. The syntax of open has two forms:

int open(const char *path, int flags); and


int open(const char *path, int flags, mode_t modes);

The first form is normally used to open an existing file, and the second form to open a
file and to create a file if it does not exist already. Both forms returns an integer called the
file descriptor. The file descriptor will be used for reading from and writing to the file. If
the file cannot be opened or created, it returns -1. The first parameter path in both forms
sPecifies the file name to be opened or created. The second parameter (flags) specifies
how the file may be used. The following list some commonly used flag values.
Flag Description
O_RDONLY open for reading only
O_WRONLY open for writing only
O_RDWR open for reading and writing
O_NONBLOCK do not block on open
O_APPEND append on each write
O_CREAT create file if it does not exist
O_TRUNC truncate size to 0
O_EXCL error if create and file exists
O_SHLOCK atomically obtain a shared lock
O_EXLOCK atomically obtain an exclusive lock
O_DIRECT eliminate or reduce cache effects
O_FSYNC synchronous writes
O_NOFOLLOW do not follow symlinks

The flag (O_CREAT) may be used to create the file if it does not exist. When this flag is
used, the third parameter (modes) must be used to specify the file access permissions
for the new file. Commonly used modes (or access permissions) include

Octal Description
Constant Name
/* RWX mask for owner */
Value
/* R for owner */ /* W
S_IRWXU 0000700 for owner */ /* X for
owner */
S_IRUSR 0000400 /* RWX mask for other */
S_IWUSR 0000200
/* R for other */ /* W
S_IXUSR 0000100 for other */ /* X for
S_IRWXO 0000007 other */
S_IROTH 0000004
S_IWOTH 0000002
S_IXOTH 0000001

R: read, W: write, and X:


executable
For example, to open file "tmp.txt" in the current working directory for reading
and writing:

fd = open("tmp.txt", O_RDWR);

To open "sample.txt" in the current working directory for appending or create it, if it
does not exist, with read, write and execute permissions for owner only:

fd = open("tmp.txt", O_WRONLY|O_APPEND|O_CREAT, S_IRWXU);

A file may be opened or created outside the current working directory. In this case, an
absolute path and relative path may prefix the file name. For example, to create a file
in /tmp directory:

open("/tmp/tmp.txt", O_RDWR);

Read from files

The system call for reading from a file is read. Its syntax is

ssize_t read(int fd, void *buf, size_t nbytes);

The first parameter fd is the file descriptor of the file you want to read from, it is
normally returned from open. The second parameter buf is a pointer pointing the
memory location where the input data should be stored. The last parameter nbytes
specifies the maximum number of bytes you want to read. The system call returns the
number of bytes it actually read, and normally this number is either smaller or equal to
nbytes. The following segment of code reads up to 1024 bytes from file tmp.txt:

int actual_count = 0;
int fd = open("tmp.txt", O_RDONLY);
void *buf = (char*) malloc(1024);
actual_count = read(fd, buf, 1024);

Each file has a pointer, normally called read/write offset, indicating where next read will
start from. This pointer is incremented by the number of bytes actually read by the read
call. For the above example, if the offset was zero before the read and it actually read
1024 bytes, the offset will be 1024 when the read returns. This offset may be changed by
the system call lseek, which will be covered shortly.

Write to files

The system call write is to write data to a file. Its syntax is

ssize_t write(int fd, const void *buf, size_t nbytes);


It writes nbytes of data to the file referenced by file descriptor fd from the buffer pointed
by buf. The write starts at the position pointed by the offset of the file. Upon returning
from write, the offset is advanced by the number of bytes which were successfully
written. The function returns the number of bytes that were actually written, or it returns
the value -1 if failed.
Experiment ∷12

Write a C program that simulates ls Command

Output:

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<dirent.h>
void main()
{
DIR *dp;
struct dirent *dirp; dp=opendir(".");
while(dirp=(readdir(dp)!=NULL))

{
if(dirp->d_ino==0)
continue;
else
printf("%s \n",dirp->d_name);
}
}

Opendir():----

NAME
opendir - open a directory

SYNOPSIS

#include < dirent.h>

DIR *opendir(const char *dirname);

DESCRIPTION

The opendir() function shall open a directory stream corresponding to the directory
named by the dirname argument. The directory stream is positioned at the first entry. If
the type DIR is implemented using a file descriptor, applications shall only be able to
open up to a total of {OPEN_MAX} files and directories. RETURN VALUE

Upon successful completion, opendir() shall return a pointer to an object of type DIR.
Otherwise, a null pointer shall be returned and errno set to indicate the error.
Ref : http://www.opengroup.org/onlinepubs/009695399/functions/opendir.html

readdir():---

NAME
readdir, readdir_r - read a directory

SYNOPSIS

#include < dirent.h>

struct dirent *readdir(DIR *dirp);

int readdir_r(DIR *restrict dirp, struct dirent *restrict entry, struct dirent
**restrict result);

DESCRIPTION

The type DIR, which is defined in the <dirent.h> header, represents a directory stream,
which is an ordered sequence of all the directory entries in a particular directory.
Directory entries represent files; files may be removed from a directory or added to a
directory asynchronously to the operation of readdir().

The readdir() function shall return a pointer to a structure representing the directory entry
at the current position in the directory stream specified by the argument dirp, and position
the directory stream at the next entry. It shall return a null pointer upon reaching the end
of the directory stream. The structure dirent defined in the <dirent.h> header describes a
directory entry.

The readdir() function shall not return directory entries containing empty names. If
entries for dot or dot -dot exist, one entry shall be returned for dot and one entry shall
be returned for dot-dot; otherwise, they shall not be returned.

The pointer returned by readdir() points to data which may be overwritten by another
call to readdir() on the same directory stream. This data is not overwritten by another
call to readdir() on a different directory stream.

If a file is removed from or added to the directory after the most recent call to opendir()
or rewinddir(), whether a subsequent call to readdir() returns an entry for that file is
unspecified.
The readdir() function may buffer several directory entries per actual read operation;
readdir() shall mark for update the st_atime field of the directory each time the
directory is actually read.

After a call to fork(), either the parent or child (but not both) may continue
processing the directory stream using readdir(), rewinddir(),or seekdir().If both the
parent and child processes use these functions, the result is undefined.

If the entry names a symbolic link, the value of the d_ino member is unspecified.

The readdir() function need not be reentrant. A function that is not required to be
reentrant is not required to be thread-safe.

The readdir_r() function shall initialize the dirent structure referenced by entry to
represent the directory entry at the current position in the directory stream referred to
by dirp, store a pointer to this structure at the location referenced by result, and
position the directory stream at the next entry.

The storage pointed to by entry shall be large enough for a dirent with an array of
char d_name members containing at least {NAME_MAX}+1 elements.

Upon successful return, the pointer returned at *result shall have the same value as the
argument entry. Upon reaching the end of the directory stream, this pointer shall have
the value NULL.

The readdir_r() function shall not return directory entries containing empty names.

If a file is removed from or added to the directory after the most recent call to
opendir() or rewinddir(), whether a subsequent call to readdir_r() returns an entry
for that file is unspecified.

The readdir_r() function may buffer several directory entries per actual read
operation; the readdir_r() function shall mark for update the st_atime field of the
directory each time the directory is actually read.

Applications wishing to check for error situations should set errno to 0 before calling
readdir(). If errno is set to non-zero on return, an error occurred.

RETURN VALUE

Upon successful completion, readdir() shall return a pointer to an object of type struct
dirent. When an error is encountered, a null pointer shall be returned and errno shall
be set to indicate the error. When the end of the directory is encountered, a null pointer
shall be returned and errno is not changed.

If successful, the readdir_r() function shall return zero; otherwise, an error number
shall be returned to indicate the error.
<dirent.h> Structure :----

The <dirent.h> header shall define the following type:

DIR A type representing a directory stream.

It shall also define the structure dirent which shall include the following members:

ino_t d_ino File serial number.


char d_name[] Name of entry.

The type ino_t shall be defined as described in <sys/types.h>.

The character array d_name is of unspecified size, but the number of bytes
preceding the terminating null byte shall not exceed {NAME_MAX}.

The following shall be declared as functions and may also be defined as macros.
Function prototypes shall be provided.

int closedir(DIR *);


DIR *opendir(const char *);
struct dirent *readdir(DIR *);
int readdir_r(DIR *restrict, struct dirent *restrict,
struct dirent **restrict);
void rewinddir(DIR *);
[
void seekdir(DIR *, long);
long telldir(DIR *);

Ref: http://www.opengroup.org/onlinepubs/009695399/functions/readdir.html

More Programs :
1. Write a non recursive shell script which accepts any number of arguments and
prints them in the reverse order (for example, if the script is named rags, then
executing rags ABC should produce CBA on the standard output

Program :
a=$#
echo "Number of arguments are" $a
x=$*
c=$a
res=''
while [ 1 -le $c ]
do
c=`expr $c - 1`
shift $c
res=$res' '$1
set $x
done
echo Arguments in reverse order $res

Output
sh 1prg.sh a b c
No of arguments arguments are 3
Arguments in reverse order c b a

2. Write a shell script that accepts two file names as arguments, checks if the
permissions for these files are identical and if the permissions are identical,
output common permissions and otherwise output each file name followed by its
permissions.

Program :

if [ $# -ne 2 ]
then
echo "pass 2 argument"
exit
fi
echo enter file name
read f1
echo enter the second file name
read f2
p1=`ls -l $f1 | cut -c 2-10`
p2=`ls -l $f2 | cut -c 2-10`
if [ $p1 = $p2 ]
then
echo permissions are same
echo $p1
else
echo permissions are different
echo permission of file $f1 is $p1
echo permission of file $f2 is $p2
fi

Output:
enter file name
10a.sh
enter the second file name
2a.sh
permissions are same
rw-r--r—
enter file name
1
enter the second file name
10a.sh
permissions are different
permission of file 1 is rwxrwxrwx
permission of file 2 is rw-r--r—

3. Write a shell script that takes a valid directory name as an argument and
recursively descend all the subdirectories, finds the maximum value to the
standard output.

Program:

clear
if [ $# -ne 1 ]
then
echo –e “\n\nInvalid Number of arguments passed\n”
exit
fi
cd $1
echo The directory name is $1
set -- ` ls -lR| grep -v "^d" |sort +4 -5 -rn`
echo "size of the largest file is $5 blocks"

Output
sh 2a.sh rv
The directory name is rv
size of the largest file is 1321 blocks

4. Aim to accepts a path name and creates all the components in that path
name as directories.
Program:
temp=IFS
IFS=/
i=$#
for i in $*
do
if [ -f $i ]
then
exit
fi
if [ -d $i ]
then
cd $i
else
mkdir $i
echo $i is in `pwd`
cd $i
fi
done
IfS=$temp

Output
sc@cselinux:~$ sh 2b.sh d1 d2 d3
d1 is in home sc
d2 is in home sc d1
d3 is in home sc d1 d2

5. Aim to show the printing of their corresponding home directories by accepting


valid log-in names as arguments.

Program:

for nam in $*
do
y=`grep "$nam" /etc/passwd | cut -d ":" -f1`
if [ -n $y ]
then
if [ "$y" = "$nam" ]
then
x=` grep "$nam" /etc/passwd | cut -d ":" -f6`
echo "home directory of $nam is $x"
else
echo "$nam doesn't have an account "
fi
fi
done
Output :

sh 3a.sh cse101
home directory of cse101 is /home/cse101
sh 3a.sh cse
cse does not have an account

6. Aim to implement terminal locking (similar to the lock command). No time


limit need be implemented for the lock duration.

Program

clear
stty -echo
echo "enter password to lock the terminal"
read pass1
echo " Re-enter password"
read pass2
if [ "$pass1" = "$pass2" ]
then
echo "system is locked"
echo "enter password to unlock"
trap ``/1 2 3 9 15 18
while true
do
read pass3
if [ $pass1 = $pass3 ]
then echo "system unlocked"
stty echo
exit
else
echo "password mismatch"
fi
done
else
echo "password mismatch"
stty echo
fi

Output:

enter the password to lock terminal :****


re-enter the password:****
system is locked
enter the password to unlock:****
system unlocked
enter the password to lock terminal:********
re-enter the password:****
password mismatch

7. Create a script file called file properties that reads a file name entered and
outputs
its properties

Program:

echo enter a filename


read file
if [ -f $file ]
then
set -- `ls -l $file`
echo file permission $1
echo number of link $2
echo user name $3
echo owner name $4
echo block size $5
echo date of modification $6
echo time of modification $7
echo name of file $8
else
echo file does not exit
fi

Output

1)
enter a filename 10a.sh
file permission -rw-r--r--
number of links 1
user name sc
owner name sc
block size 566
date of modification 2009-01-29
time of modification 02:30
name of file 10a.sh

2)

enter a filename
test
file does not exit
8. Write a shell script that accept one or more file names as argument and convert
all of them to uppercase, provided they exist in current directory.

Program:

clear
if [ $# -eq 0 ]
then “echo enter the arguments”
exit
fi
for i in $*
do
if [ -f $i ]
then
echo it is a valid file
echo Contents of file before converting
cat $i
echo Contents of file after converting
tr '[a-z]' '[A-Z]' < $i
k=`ls $i | tr '[a-z]' '[A-Z]'`
mv $i $k
echo file $i renamed as $x
ls
else
echo file does not exist
fi
done

Output

$sh 4b.sh test


It is a valid file
file test renamed as TEST
10b.sh 12b.awk 1bprg.sh 2a.sh 4a.sh 6a.sh 8a.sh a1 d1 first rv TEST x
$sh 4b.sh program1
file does not exist

9. write a shell script that display all the links to a file specified as the firt
argument to the script. The second argument, which iws optional, can be used to
specify in which the search is to begin in current working directory, In either
case, the starting directory as well as all its subdirectories at all levels must be
searched. The script need not include any error checking

Program:
if [ $# -eq 1 ]
then pwd>tm
cat tm
else
tm=$2
echo "$tm"
fi
t1=`ls -aliR | grep "$1" | cut -c 1-8 `
ls -alir $tm | grep "$t1" |cut -c 65- > t2
echo "the links are"
cat t2

Output

sh 5a.sh first
links are
13582397 -rw-r--r-- 1 sc sc 10 2009-01-29 01:56 first
sc@cselinux:~$ ln first temp
sc@cselinux:~$ sh 5a.sh temp
links are
13582397 -rw-r--r-- 2 sc sc 10 2009-01-29 01:56 first
13582397 -rw-r--r-- 2 sc sc 10 2009-01-29 01:56 temp

10. Write a shell script that accepts as filename as argument and display its
creation time if file exists and if it does not send output error message

Program:

if [ $# -eq 0 ]
then
echo enter the arguments
exit
fi
if [ –f $1 ]
then
time=`ls –l $1 | cut –c 44-55`
echo file $1 was created on $time
else
echo file $1 does not exist
fi

Output :

sh 5b.sh temp
file temp was created on 2009-01-29 01:56
sh 5b.sh temp11
file temp11 does not exist

11. Write a shell script to display the calendar for current month with current
datereplaced by * or ** depending on whether the date has one digit or two digits.

Program:
d=`date +%d`
cal > cal1
if [ $d -le 9 ]
then
sed 's/'$d'/*/' cal1
exit
fi
sed 's/'$d'/ **/' cal1

Output :

January 2009
Su Mo Tu We Th Fr Sa
123
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 **

12. Write a shell script to find smallest of 3 numbers that are read from keyboard.

Program:

echo enter first number


read a
echo enter second number
read b
echo enter third number
read c
if [ $a -eq $b -a $b -eq $c ]
then
echo all numbers are equal
exit
fi
if [ $a -lt $b ]
then
s1=$a
s2=$b
else
s1=$b
s2=$a
fi
if [ $s1 -gt $c ]
then
s2=$s1
s1=$c
fi
echo "smallest number is " $s1

Output :

enter first number:54


enter second number:67
enter third number :22
smallest number is 22
enter first number:50
enter second number:50
enter third number :50
all numbers are equal

13. Write a shell script using expr command to read in a string and display a
suitable message if it does not have atleast 10 characters

Program:

clear
echo enter the string
read s
l=`expr length $s`
if [ $l -gt 10 ]
then
echo "string has more than 10 characters"
else
echo "string has less than 10 characters"
fi

Output :

enter the string


sajipaul
string has less than 10 characters
enter the string
engineering
string has more than 10 characters
14. Write a shell script to compute the sum of number passed to it as argument on
command line and display the result.

Program:

clear
if [ $# -eq 0 ]
then
echo "no arguments"
exit
else
sum=0
for i in $*
do
sum=`expr $sum + $i`
done
echo "sum of the numbers is "$sum
fi

Output

$ sh 7b.sh 10 10 20
sum of the numbers is 40
$ sh 7b.sh 10 100 200
sum of the numbers is 310

15. Aim to compute gross salary of an employee ,accordingly to rule given below.
If basic salary is <15000 then HRA =10% of basic and DA =90% of basic
If basic salary is >=15000 then HRA =500 and DA =98% of basic

Program:

clear
echo enter the basic
read basic
if [ $basic -lt 15000 ]
then
hra=`echo "scale=2; $basic * 0.1" | bc`
da=`echo "scale=2; $basic * 0.9" | bc`
else
hra=500
da=`echo "scale=2; $basic * 0.98" | bc`
fi
gs=`echo "scale=2;$basic +$hra +$da" | bc`
echo " gross =" $gs
echo "hra =" $hra
echo "da =" $da

Output

$ sh 8a.sh
enter the basic pay
1000
gross = 2000.0
hra = 100.0
da = 900.0
$ sh 8a.sh
enter the basic
20000
gross = 40100.00
hra = 500
da = 19600.00

16. Write a shell script to delete all lines containing a specific word in one or more
file supplied as argument to it.

Program:

clear
if [ $# -eq 0 ]
then
echo no arguments passed
exit
fi
echo the contents before deleting
for i in $*
do
echo $i
cat $i
done
echo enter the word to be deleted
read word
for i in $*
do
grep -vi "$word" $i > temp
mv temp $i
echo after deleting
cat $i
done

Output:
$ sh 8b.sh test1
the contents before deleting
test1
hello rvce
hello cse
bangalore
mysore city
enter the word to be deleted
city
after deleting
hello rvce
hello cse
bangalore
$ sh 8b.sh
no argument passed

16. Write a shell script that gets executed displays the message either “Good
Morning”or “Good Afternoon “ or “Good Evening” depending upon the time at
which user logs in.

Program:

hournow=’date | cut –c 12-13’


user=’echo $HOME | cut –d”/” –f 2’
case $hournow in
[0-1][0-1]|0[2-9]) echo “Good Morning Mr/Ms : $user”;;
1[2-5])echo “Good Afternoon Mr/Ms :$user”;;
1[6-9])echo “Good Evening Mr/Ms :$user”;;
esac
Output :

$ sh .bash_profile
good morning sc

17. A shell script that accepts a list of filenames as its arguments, counts and
reports the occurrence of each word that is present in the first argument file on
other argument files.

Program:

if [ $# -ne 2 ]
then
echo "Error : Invalid number of arguments."
exit
fi
str=`cat $1 | tr '\n' ' '`
for a in $str
do
echo "Word = $a, Count = `grep -c "$a" $2`"
done

Output :

$ cat test
hello rvce cse
$ cat test1
hello rvce cse
hello rvce cse
hello
$ sh 1.sh test test1
Word = hello, Count = 3
Word = rvce, Count = 2
Word = cse, Count = 2

18. Write a shell script that determines the period for which specified user is
working on the system.

Program:

echo “Enter the Login Name of a User”


read name
count=`who | grep –wo “$user” | wc –c`
if [ $count –eq 0 ]
then
echo “invalid user”
exit
fi
if [$count –gt 2 ]
then
echo “Multiple Login”
else
lt=`who | grep “user” | cut –c 34-38`
lh=`echo $lt | cut –c 1-2`
lm=`echo $lt | cut –c 4-5`
ch=`date +%H`
cm=`date +%M`
if [ $cm –gr $lm ]
then
sm=`expr $cm -$lm`
sh=`expr $ch - $lh`
else
sm=`expr 60 - $lm -$cm`
sh=`expr $ch - $lh – 1`
fi
echo “ The user is logged in from $sh hour $sm minutes”
fi

Output :

1) Enter the user name :cse219


The user is logged in from 1 hour 20 minutes
2) Enter the user name:abc
Invalid user

19. Write a shell script that reports the logging in of a specified user within one
minute after he/she logs in. The script automatically terminates if the specified
user does not login during a specified period of time

Program:

echo ‘Enter the login name of the user:”


read user
period=0
while [ true]
do
var=`who | grep –w “$user”`
len=`echo “$var | wc –c`
if [ $len –gt 1 ]
then
echo “$user logged in $tm seconds”
exit
else
sleep 1
tm=`expr $tm + 1`
fi
if [ $tm –eq 61 ]
then
echo “$user did not login within 1 minute”
exit
fi
done

Output :

Enter the login name of the user :cse219


cse219 logged in 25 seconds
Enter the login name of the user :cse250
cse250 did not login within 1 minute

20. Write a shell script that accepts two integers as its arguments and computes
the value of first number raised to the power of the second number.

Program:

if [ $# -ne 2 ]
then
echo "Error : Invalid no. of arguments."
exit
fi
pwr=`echo "$1 ^ $2" | bc`
echo "$1 ^ $2 = $pwr"

Output:

$sh 11a.sh 2 3
2^3 = 8

21. Write a shell script that accepts a filename, starting and ending line numbers
as arguments and displays all the lines between the given line numbers.

Program:

if [ $# -ne 3 ]
then echo "Error : Invalid number of arguments."
exit
fi
if [ $2 -gt $3 ]
then
echo "Error : Invalid range value."
exit
fi
l=`expr $3 - $2 + 1`
cat $1 | tail +$2 | head -$l

Output:

$sh 11b.sh test 5 7


abc 1234
def 5678
ghi 91011
22. Write a shell script that folds long lines into 40 columns. Thus any line that
exceeds 40 characters must be broken after 40th ; a\ is to be appended as the
indication of folding and the processing is to be continued with the residue. The
input is to be through a text file created by the user.

Program:

echo “ Enter the filename :\c”


read fn
for ln in `cat $fn`
do
lgth=`echo $ln | wc -c`
lgth=`expr $lgth - 1`
s=1;e=5
if [ $lgth -gt 40 ]
then
while [ $lgth -gt 40 ]
do
echo "`echo $ln | cut -c $s-$e`\\"
s=`expr $e + 1`
e=`expr $e + 40`
lgth=`expr $lgth - 40`
done
echo $ln | cut -c $selse
echo $ln
fi
done
echo “File Folded ”

OUTPUT

$sh 12a.sh
Enter the filename : test
File Folded

23. Write a awk script that accepts date argument in the form of mm-dd-yy and
displays it in the form if any ,month ,year. The script should check the validity of
the argument and in the case of error, display a suitable message.

BEGIN
{
system(“clear”);
da=”312831303130313130313031”
mo=”JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC”
mm=substr(ARGV[1],1,2)
dd=substr(ARGV[1],4,2)
yy=substr(ARGV[1],7,4)
if(dd > substr(da,2-mm-1,2) || (mm>12) || ARGC !=2)
print “Invalid date”
else
print “The day is %d \n The month is %s \n
The year is %d \n”,dd,substr(mo,3*mm-2,3)yy
}

Output :

$awk -f 12b.awk 12-10-2008


The day is 10
The month is OCT
The year is 2008

24. Write an awk script to delete duplicated line from a text file. The order of the
original lines must remain unchanged.

Program:
BEGIN
{
a[n++]=$0
}
END
{
for(i=0;i<n;i++)
{
flag=0;
for(j=0;j<i;j++)
{
if( a[i] == a[j])
{
flag=1;
break;
}
}
if (flag == 0)
printf “%s \n”, a[i]
}
}

Output :

$ cat test
college
college
bangalore
$ awk -f 13a.awk test
college
Bangalore

25. Write an awk script to find out total number of books sold in each discipline
as well as total book sold using associate array down table as given
electrical 34
mechanical 67
electrical 80
computers 43
mechanical 65
civil 198
computers 64

Program:

BEGIN {print “TOTAL NUMBER OF BOOKS SOLD IN EACH CATEGORY”}


{ books[$1]+=$2}
END {
for (item in books)
{
printf (“ %s sold= %d\n”,item,books[item]}
total +=books[item]
}
printf(”Total books sold=%d”,total)
}

Output :

TOTAL NUMBER OF BOOKS SOLD IN EACH CATEGORY


electrical 114
mechanical 137
computers 107
civil 198
Total books sold = 556

26. Write an awk script to compute gross salary of an employee accordingly to


rule given below If basic salary < 10000 then DA = 45% of the basic and HRA
=15% of basic If basic salary >= 10000 then DA =50% of the basic and HRA
=20% of basic

Program:

BEGIN { printf "Enter the Basic Pay : Rs. "


getline bp < "/dev/tty"
if(bp<10000)
{ hra=.15*bp
da=.45*bp
}
else
{
hra=.2*bp
da=.5*bp
}
gs=bp+hra+da
printf "Gross Salary = Rs. %.2f\n", gs
}

Output :

$awk –f 13.awk
Enter the Basic Pay : Rs. 10000
Gross Salary = Rs. 17000

S-ar putea să vă placă și