Presentation is loading. Please wait.

Presentation is loading. Please wait.

Library Functions The UNIX system provides a large number of C functions as libraries. Some of these implement frequently used operations, while others.

Similar presentations


Presentation on theme: "Library Functions The UNIX system provides a large number of C functions as libraries. Some of these implement frequently used operations, while others."— Presentation transcript:

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

2 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

3 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

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

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

6 Some Useful Library Functions

7 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

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

9

10 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

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

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

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

14 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,

15 Formatted I/O in c Scanf(),fscanf(),sscanf()
Printf(),fprintf(),sprintf()

16 KERNEL SUPPORT FOR FILES
The kernel represents open files using three related data structures: File Descriptor table File table i-node table

17 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

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

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

20

21

22 Two independent processes with the same file open

23 System Calls System call is a request to the kernel to provide specific service. System calls are interface to the kernel.

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

25 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

26 Open 1st parameter :path
The name of the file or device to be opened is passed as a parameter, path;

27 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

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

29 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

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

31 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

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

33 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’

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

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

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

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

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

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

40 Declaration of stat structure
struct 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*/ }

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

42 The following flags are defined for the st_mode field:
S_IFMT bit mask for the file type bit fields S_IFSOCK socket S_IFLNK symbolic link S_IFREG regular file S_IFBLK block device S_IFDIR directory S_IFCHR character device S_IFIFO FIFO S_ISUID set UID bit S_ISGID set-group-ID bit (see below) S_ISVTX sticky bit (see below) S_IRWXU mask for file owner permissions S_IRUSR owner has read permission S_IWUSR owner has write permission S_IXUSR owner has execute permission S_IRWXG mask for group permissions S_IRGRP group has read permission S_IWGRP group has write permission SIXGRP group has execute permission S_IRWXO mask for permissions for others (not in group) S_IROTH others have read permission S_IWOTH others have write permission S_IXOTH others have execute permission

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

44 lseek() whence new position 0 (SEEK_SET) offset bytes into the file
#include<sys/types.h> #include<unistd.h> long lseek(int file_descriptor, long offset, int whence) whence new position 0 (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


Download ppt "Library Functions The UNIX system provides a large number of C functions as libraries. Some of these implement frequently used operations, while others."

Similar presentations


Ads by Google