Library Functions • The UNIX system provides a large number of C functions as libraries.

Download Report

Transcript Library Functions • The UNIX system provides a large number of C functions as libraries.

Library Functions
• The UNIX system provides a large number of C
functions as libraries. Some of these implement
frequently used operations, while others are very
specialized in their application.
• Wise programmers will check whether a library
function is available to perform a task before
writing their own version. This will reduce
program development time.
• The standard C library functions are declared
in a set of header files that are commonly
placed in the /usr/include directory on UNIX
systems.
• The archive and shared libraries that contain
the object code of these library functions are
the libc.a (static library)and libc.so(dynamic
library), respectively. These libraries are
commonly placed in the /usr/lib directory on
UNIX system
Finding Information about Library
Functions
• The UNIX manual has an entry for all available
functions. Function documentation is stored in
section 3 of the manual, and there are many
other useful system calls in section 2. If you
already know the name of the function you want,
you can read the page by typing (to find about
strcat).
• $man 3 strcat
• If you don't know the name of the function, a full
list is included in the introductory page for
section 3 of the manual. To read this, type
$man 3 intro
printf(“a");
write(STDOUT_FILENO, “b", 1);
printf(“c\n");
Output: bac
Reason:
•write is a system call -- it is implemented by the interface between user mode (where
programs like yours run) and the operating system kernel (which handlesthe actual
writing to disk when bytes are written to a file).
•printf is a C standard library function -- it is implemented by library code loaded into your
user mode program.
•The C standard library output functions buffer their output, by default until end-of-line is
reached. When the buffer is full or terminated with a newline, it is written to the file via a
call to write from the library implementation.
•Therefore, the output via printf is not sent to the operating system write immediately. In
your example, you buffer the letter 'u', then immediately write the letter 'm', then
append "d\n" to the buffer and the standard library makes the call
write(STDOUT_FILENO, "ud\n");
Use of Library Functions
• To use a function, ensure that you have made the required
#includes in your C file. Then the function can be called as
though you had defined it yourself.
• Some libraries require extra options before the compiler
can support their use. For example, to compile a program
including functions from the math.h library the command
might be
• cc mathprog.c -o mathprog -lm
• The final -lm is an instruction to link the maths library with
the program. The manual page for each function will
usually inform you if any special compiler flags are
required.
Some Useful Library Functions
Static Libraries Vs Dynamic libraries:
• Static libraries are linked into your executable at link
time so are fixed at that point.
• For dynamic linking, only a reference to the library is
linked in at link time. The dynamic library (the actual
code) is linked to your executable at load time, when
you run your program.That means you can change the
dynamic library at any time and you'll use the new one
the next time you load the program
Library naming conventions:
• Libraries are typically names with the prefix "lib". This is
true for all the C standard libraries. When linking, the
command line reference to the library will not contain
the library prefix or suffix.
• Thus the following link command:
• gcc src-file.c -lm -lpthread
The libraries referenced in this example for inclusion
during linking are the math library and the thread
library. They are found in /usr/lib/libm.a and
/usr/lib/libpthread.a.
Standard I/O and Formatted I/O in C
• The standard I/O library (stdio) and its header
file, stdio.h, provide a versatile interface to lowlevel I/O system calls.
• The library, now part of ANSI standard C, provides
many sophisticated functions for formatting
output and scanning input. It also takes care of
the buffering requirements for devices.
• whereas the system calls are not part of ANSI C
C Stream Pointers
• You need to open a file to establish an access path. This
returns a value that is used as a parameter to other I/O
library functions.
• This return value is called a stream and is implemented as a
pointer to a structure, a FILE *.
• Three file streams are automatically opened when a
program is started. They are stdin, stdout, and stderr. These
are declared in stdio.h and represent the standard input,
output, and error output, respectively, which correspond to
the low-level file descriptors 0, 1, and 2.
What is FILE pointer in c programming
language?
• C communicates with files using a new data type called a file pointer.
• FILE pointer is struct data type which has been defined in standard library
stdio.h. This data type points to a stream or a null value. It has been defined
in stdio.h as
typedef struct{
short
level;
unsigned
flags;
char
fd;
unsigned char hold;
short
bsize;
unsigned char *buffer, *curp;
unsigned
istemp;
short
token;
} FILE;
What is file pointer and its working
method?
• For files you want to read or write, you need a file pointer, e.g.:FILE *fp;
• when a pointer is pointing to the address of a file then it is called as a file pointer.
• File pointer is the pointer which holds the address of the file which is opened
either in read or write or append or binary modes(r,w,a,r+,w+,a+,b).
FILE *fp;
This is the declaration of the file pointer.
here in the above statement we are declaring a file pointer.
there are many modes of opening a file. they are read ,write,append ..
•
they are as follows..
fp=fopen("filename.c",'r');
above statement is opening a file in read mode..
Standard I/O Functions in C
• fopen( )
• fread( ), fgets( ),gets( ),fgetc( ) , getc( ) ,
getchar(),
• fwrite(), fputs(), puts(),fputc(),putc(),putchar(),
• ftell(),fseek(),fgetpos(),fsetpos(),rewind()
• fflush(), fclose,
Formatted I/O in c
• Scanf(),fscanf(),sscanf()
• Printf(),fprintf(),sprintf()
KERNEL SUPPORT FOR FILES
• The kernel represents open files using three
related data structures:
1. File Descriptor table
2. File table
3. i-node table
File Descriptor table
• Each process has its own separate file descriptor table whose
entries are indexed by the process’s open file descriptors.
• Each open descriptor entry points to an entry in the file table.
• File descriptors
• Each UNIX process has 20 file descriptors at it disposal,
numbered 0 through 19.
• The first three are already opened when the process begins
0: The standard input
1: The standard output
2: The standard error output
• When the parent process forks a process, the child process
inherits the file descriptors of the parent
File table
• The set of open files is represented by a file table that
is shared by all processes.
• Each file table entry consists of (for our purposes) the
current file position, a reference count of the number
of descriptor entries that currently point to it, and a
pointer to an entry in the i-node table.
• Closing a descriptor decrements the reference count
in the associated file table entry. The kernel will not
delete the file table entry until its reference count is
zero.
i-node table
• Like the file table, the i-node table is shared by all
processes. Each entry contains most of the
information in the stat structure, including the st
mode and st size members.
Two independent processes with the same file
open
System Calls
• System call is a request to the kernel to
provide specific service.
• System calls are interface to the kernel.
UNIX FILE I/O -Low Level File Access
(UNIX FILE API)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
open()
creat()
read()
write()
close()
lseek()
stat()
fstat()
ioctl()
umask()
dup()
dup2()
link)()
unlink()
fcntl()
chmod()
chown()
chgrp()
open
• To open or create a file
• Prototype is :
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int open(const char *path, int oflags);
int open(const char *path, int oflags, mode_t mode);
• Returns: new file descriptor if OK, −1 on error
Open
1st parameter :path
• The name of the file or device to be opened is
passed as a parameter, path;
Open
2nd parameter
• the oflags parameter is used to specify actions to be taken on
opening the file.
• The oflags are specified as a combination of a mandatory file
access mode and other optional modes. The open call must
specify one of the file access modes shown in the following
table:
Mode
Description
O_RDONLY
Open for read-only
O_WRONLY
Open for write-only
O_RDWR
Open for reading and writing
open
• The call may also include a combination (using a bitwise OR) of the
following optional modes in the oflags parameter:
•
•
O_APPEND: Place written data at the end of the file.
O_TRUNC: Set the length of the file to zero, discarding existing
contents.
• O_CREAT: Creates the file, if necessary, with permissions given in
mode.
• O_EXCL: Used with O_CREAT, ensures that the caller creates the
file. The open is atomic; that is, it’s performed with just one
function call. This protects against two programs creating the file at
the same time. If the file already exists, open will fail.
Open
3rd parameter :mode
• When you create a file using the O_CREAT flag with open,
you must use the three-parameter form. mode, the third
parameter, is made from a bitwise OR of the flags defined
in the header file sys/stat.h. These are:
• S_IRUSR: Read permission, owner
• S_IWUSR: Write permission, owner
• S_IXUSR: Execute permission, owner
• S_IRGRP: Read permission, group
• S_IWGRP: Write permission, group
• S_IXGRP: Execute permission, group
• S_IROTH: Read permission, others
• S_IWOTH: Write permission, others
• S_IXOTH: Execute permission, others
OPEN
Examples
• fd=open (“myfile”, O_CREAT, S_IRUSR|S_IXOTH)
•
fd = Open("foo.txt", O_RDONLY, 0);
•
fd = Open("foo.txt", O_WRONLY|O_APPEND, 0);
creat( ) system call
• To create new file
• The prototype for the creat() system call is:
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
Int creat(const char *path, mode_t mode);
• Returns: new file descriptor if OK, −1 on error
• Here path is the filename
• Mode is same as in open system call
read() system call
• The read system call reads up to n bytes of data from
the file associated with the file descriptor fd and places
them in the data area buf.
#include <unistd.h>
size_t read( int fd, void *buf, size_t nbytes );
• On successful completion the function returns the
number of bytes actually read. It returns 0 if end of file
is reached and -1 on error.
Write() system call
• Here’s the syntax:
#include <unistd.h>
size_t write(int fildes, const void *buf, size_t nbytes);
• The write() function writes the number of bytes
specified by ‘nbytes’ from the buffer ‘buf’ into the
file pointed by ‘fd’
Close() system call
• To terminate the association between a file
descriptor, fd, and its file. The file descriptor
becomes available for reuse.
• It returns 0 if successful and –1 on error.
#include <unistd.h>
int close(int fd);
Example programs
•
This program, simple_read.c, copies the first 128 bytes of the standard input to the
standard output. It copies all of the input if there are fewer than 128 bytes.
#include <unistd.h>
#include <stdlib.h>
int main()
{
char buffer[128];
int nread;
nread = read(0, buffer, 128);
if (nread == -1)
write(2, “A read error has occurred\n”, 26);
if ((write(1,buffer,nread)) != nread)
write(2, “A write error has occurred\n”,27);
exit(0);
}
C program to implement cp command
using system calls
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
void main()
{
int fd1,fd2,n;
char c,src[20],dst[20];
printf("Read source file : ");
scanf("%s", src);
printf("Read destination file : ");
scanf("%s“,dst);
fd1=open(src,O_RDONLY);
fd2=open(dst,O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR
|S_IXUSR);
if(fd1==-1 || fd2==-1)
printf("Files cannt be opened");
else
{
while((n=read(fd1,&c,1))>0)
write(fd2,&c,1);
}
close(fd1);
close(fd2);
}
stat(),fstat(),lstat() system calls
• stat ,fstat functions retrieve file attributes of a given file.
• lstat return the symbolic link file attributes, not the file it
refers to .
• the syntax:
#include <unistd.h>
#include <sys/types.h>
int fstat(int fildes, struct stat *buf);
int stat(const char *path, struct stat *buf);
int lstat(const char *path, struct stat *buf);
• These functions return 0 if they succeed or -1 if they fail.
Arguments of stat,fstat,lstat
• The first argument of stat is a file path name,
whereas the first argument of fstat is a file
descriptor.
• The second argument to stat,fstat and lstat is
the address of a struct stat- typeed variable
• The struct stat data type is defined in the
<sys/stat.h> header
• The <sys/stat.h> header shall define the
structure of the data returned by the
functions fstat(), lstat(), and stat().
Declaration of stat structure
struct stat
{
dev_t st_dev;
ino_t st_ino;
mode_t st_mode;
nlink_t st_nlink:
uid_t st_uid
gid_t st_gid
dev_t st_rdev;
off_t st_size
time_t st_atime;
time_t st_mtime;
time_t st_ctime;
}
/* file system ID * /
/*File inode number*/
/* contains file type and access flags*/
/* Hard Link count*/
/* File user Id*/
/* File group ID*/
/* Contains major and minor device numbers*/
/* File size in nuber of bytes*/
/* Last access time*/
/* Last modification time time*/
/* Last status change time time*/
• The following POSIX macros are defined to
check the file type using the st_mode field:
•
•
•
•
•
•
•
S_ISREG(m) is it a regular file?
S_ISDIR(m) directory?
S_ISCHR(m) character device?
S_ISBLK(m) block device?
S_ISFIFO(m) FIFO (named pipe)?
S_ISLNK(m) symbolic link?
S_ISSOCK(m) socket?
• The following flags are defined for the st_mode field:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
S_IFMT
S_IFSOCK
S_IFLNK
S_IFREG
S_IFBLK
S_IFDIR
S_IFCHR
S_IFIFO
S_ISUID
S_ISGID
S_ISVTX
S_IRWXU
S_IRUSR
S_IWUSR
S_IXUSR
S_IRWXG
S_IRGRP
S_IWGRP
SIXGRP
S_IRWXO
S_IROTH
S_IWOTH
S_IXOTH
0170000 bit mask for the file type bit fields
0140000 socket
0120000 symbolic link
0100000 regular file
0060000 block device
0040000 directory
0020000 character device
0010000 FIFO
0004000 set UID bit
0002000 set-group-ID bit (see below)
0001000 sticky bit (see below)
00700 mask for file owner permissions
00400 owner has read permission
0200 owner has write permission
0100 owner has execute permission
00070 mask for group permissions
00040 group has read permission
00020 group has write permission
0010 group has execute permission
00007 mask for permissions for others (not in group)
00004 others have read permission
00002 others have write permission
00001 others have execute permission
lseek() system call
• The UNIX system file system treats an ordinary file as a
sequence of bytes.
• Generally, a file is read or written sequentially
-- that is from beginning to the end of the file.
• Sometimes sequential reading and writing is
not appropriate.
• Random access I/O is achieved by changing the value
of this file pointer using the lseek() syystem call.
lseek()
#include<sys/types.h>
#include<unistd.h>
long lseek(int file_descriptor, long offset, int whence)
whence
0 (SEEK_SET)
new position
offset bytes into the file
1(SEEK_CUR)
current position in the file
plus offset
2 (SEEK_END)
current end-of-file position plus
offset