Wednesday 8 July 2015

LINUX1

Image description
/*1)WRITE  A  c PROGRAM  THAT  USES  OPEN,READ,WRITE SYSTEM CALLS

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

Open() system call:
used to open an existing file or to create a new file if it does not   
 exist already.
 Syntax:
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);

Read()  System call: 
read from a file descriptor
Syntax:
ssize_t read(int fd, void *buf, size_t nbytes);

Write()  System call:
 write to a file descriptor
syntax:
ssize_t write(int fd, const void *buf, size_t nbytes);

Close() System call: 
 closes a file
Syntax:
int close(int fd);

lseek() System call
allows random access to a file by reposition the offset for next read or write
Syntax:
off_t lseek(int fd, off_t offset, int reference);

PRE_WORK:

CREATE A FILE(eg:file)
(USING cat COMMAND)

PROGRAM:
*/
#include<stdio.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
main()
{
      int fd,wcount,i;
      char buf[]="linux lab";
      fd=open("file",O_RDWR|O_CREAT,0755);
     if(fd==-1)
      {
            printf("cannot open file");
            exit(1);
      }    
      wcount=write(fd,buf,strlen(buf));
      if(wcount!=strlen(buf))
      {
            printf("write failed not enough space");
            exit(2);
      }

            lseek(fd,0,SEEK_SET);
            read(fd,0,wcount);
            printf("file contents %s\n",buf);
            close(fd);
     
}

/*
COMPILATION:
 gcc 1.c(YOUR filename.c which is saved)

EXECUTION:
./a.out file  
( file is name of the file created using cat command in pre_work )

OUTPUT:
file contents linux lab


*/

No comments:

Post a Comment