In: Computer Science
In C, write a program that makes use of the flags O_CREAT and O_EXCL, and observe what does it do when you try to open an existing file
Solution:
The observations are clearly given in the program in the form of comments
------------------------------------------------------------------------------------------------------------------------------------------------------------------
O_CREAT:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
int main(int arg, char *argv[])
{
int fd;
err = 0;
if(arg!=2)
{
printf("Usage:");
return 1;
}
/* The O_CREAT flag enables the open() System call to create a
file
If the file does not exist in the path which is given */
fd = open(argv[1],O_RDONLY|O_CREAT,S_IRWXU);
if(fd==-1)
{
printf("\n Open() System call failed [%s]",strerror(err));
return 1;
}
else
{
printf("\n Open() Succeded");
/* Here we see that the open() system call is successfully
called,
One can easily perform read operations on the file
The file needs to be closed after the operation using close().
*/
}
return 0;
}
----------------------------------------------------------------------------------------------------------------------------------------------------------------
O_EXCL
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#include <sys/types.h>
#include <string.h>
int main(int arg, char *argv[])
{
errno=0;
int fd;
if(arg!=2)
{
printf("Usage:");
return 1;
}
/* By using the O_CREAT flag, the open() system call is used to
create a file
If the file does not exist in the path which is given
then the O_EXCL flag makes sure that an error is Successfully
thrown in O_CREAT*/
fd = open(argv[1],O_RDONLY|O_CREAT|O_EXCL,S_IRWXU);
if(fd==-1)
{
printf("\n open() System call failed [%s] "
,strerror(errno));
return 1;
}
else
{
printf("\n Open() System call passed\n");
/* Here we see that the open() system call is Successful.
One can easily start read operations now
After all the work is done, please close the file which can be
easily done using close().*/
}
return 0;
}