The functions like open(), read(), write(), lseek(), stat() and close() are implemented in this program.
Example Program
#include unistd.
#include fcntl.h
#include sys/types.h
#include sys/stat.h
int main()
{
int fd,op;
char buffer[80];
char fn[20];
struct stat filestat;
printf("\nEnter U'r choice 1. Write 2. Read 3.lseek 4.Exit\n");
scanf("%d",&op);
do
{
printf("\nEnter the file name to process\n");
scanf("%s",&fn);
if (op == 1)
{
fd = open(fn,O_RDWR | O_CREAT | O_EXCL, S_IREAD | S_IWRITE);
if (fd != -1)
{
printf("%s opened for read/write access\n",fn);
write(fd,message,sizeof(message));
printf("Message written into %s ",fn);
close(fd);
}
else
printf("File %s already exists",fn);
}
else
if(op == 2)
{
fd = open(fn, O_RDWR , S_IREAD | S_IWRITE);
if (fd != -1)
{
read(fd, buffer, sizeof(message));
printf("\"%s\" was read from %s\n",buffer,fn);
}
else
printf("**** Error Reading %s ***\n",fn);
close(fd);
}
else
if(op == 3)
{
fd = open(fn,O_RDONLY);
if (fd < -1)
printf("File Error");
else
{
char buf[19];
if(read(fd,buf,20) != 20)
printf("Less content");
else
{
printf("First 20 bytes : \n %s\n ",buf);
if(lseek(fd,20,SEEK_SET) < 0)
printf("Not enough content");
else
{
if(read(fd,buf,20) != 20)
printf("Not Enough content");
else
printf("Next 20 bytes :\n%s\n",buf);
} }}
}
if(stat(fn,&filestat) < 0)
printf("File not found");
else
{
printf("\nSize of the File created is : %d bytes ",filestat.st_size);
printf("\nThe user_id of the File is : %d ",filestat.st_uid);
}
printf("\nEnter U'r choice 1. Write 2. Read 3.lseek 4.Exit\n");
scanf("%d",&op);
}
while(op != 4);
printf("\nEnd of Program 8 : File related System Calls\n");
exit (0);
}
No comments:
Post a Comment