library functions

44
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

Upload: elijah-hunter

Post on 01-Jan-2016

39 views

Category:

Documents


2 download

DESCRIPTION

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. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Library Functions

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.

Page 2: Library Functions

• 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

Page 3: Library Functions

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

Page 4: Library Functions

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");

Page 5: Library Functions

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.

Page 6: Library Functions

Some Useful Library Functions

Page 7: 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

Page 8: Library Functions

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.

Page 9: Library Functions
Page 10: Library Functions

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 low-level 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

Page 11: Library Functions

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.

Page 12: Library Functions

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;

Page 13: Library Functions

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

Page 14: Library Functions

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,

Page 15: Library Functions

Formatted I/O in c

• Scanf(),fscanf(),sscanf()• Printf(),fprintf(),sprintf()

Page 16: Library Functions

KERNEL SUPPORT FOR FILES

• The kernel represents open files using three related data structures:

1. File Descriptor table2. File table3. i-node table

Page 17: Library Functions

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

Page 18: Library Functions

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.

Page 19: Library Functions

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.

Page 20: Library Functions
Page 21: Library Functions
Page 22: Library Functions

Two independent processes with the same file open

Page 23: Library Functions

System Calls

• System call is a request to the kernel to provide specific service.

• System calls are interface to the kernel.

Page 24: Library Functions

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()

Page 25: Library Functions

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

Page 26: Library Functions

Open1st parameter :path

• The name of the file or device to be opened is passed as a parameter, path;

Page 27: Library Functions

Open2nd 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 DescriptionO_RDONLY Open for read-onlyO_WRONLY Open for write-onlyO_RDWR Open for reading and writing

Page 28: Library Functions

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.

Page 29: Library Functions

Open3rd 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

Page 30: Library Functions

OPENExamples

• 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);

Page 31: Library Functions

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

Page 32: Library Functions

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.

Page 33: Library Functions

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’

Page 34: Library Functions

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);

Page 35: Library Functions

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);}

Page 36: Library Functions

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); • • • • • • • • •

Page 37: Library Functions

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);}

Page 38: Library Functions

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.

Page 39: Library Functions

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().

Page 40: Library Functions

Declaration of stat structurestruct stat{ dev_t st_dev; /* file system ID * / ino_t st_ino; /*File inode number*/ mode_t st_mode; /* contains file type and access flags*/ nlink_t st_nlink: /* Hard Link count*/ uid_t st_uid /* File user Id*/ gid_t st_gid /* File group ID*/ dev_t st_rdev; /* Contains major and minor device numbers*/ off_t st_size /* File size in nuber of bytes*/time_t st_atime; /* Last access time*/time_t st_mtime; /* Last modification time time*/time_t st_ctime; /* Last status change time time*/}

}

Page 41: Library Functions

• 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?

Page 42: Library Functions

• The following flags are defined for the st_mode field:• S_IFMT 0170000 bit mask for the file type bit fields• S_IFSOCK 0140000 socket • S_IFLNK 0120000 symbolic link • S_IFREG 0100000 regular file • S_IFBLK 0060000 block device • S_IFDIR 0040000 directory • S_IFCHR 0020000 character device • S_IFIFO 0010000 FIFO • S_ISUID 0004000 set UID bit • S_ISGID 0002000 set-group-ID bit (see below) • S_ISVTX 0001000 sticky bit (see below) • S_IRWXU 00700 mask for file owner permissions• S_IRUSR 00400 owner has read permission • S_IWUSR 0200 owner has write permission• S_IXUSR 0100 owner has execute permission• S_IRWXG 00070 mask for group permissions • S_IRGRP 00040 group has read permission • S_IWGRP 00020 group has write permission • SIXGRP 0010 group has execute permission • S_IRWXO 00007 mask for permissions for others (not in group) • S_IROTH 00004 others have read permission • S_IWOTH 00002 others have write permission• S_IXOTH 00001 others have execute permission

Page 43: Library Functions

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.

Page 44: Library Functions

lseek()#include<sys/types.h>#include<unistd.h>long lseek(int file_descriptor, long offset, int whence)

whence new position0 (SEEK_SET) 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