I am currently using the following line to get a file descriptor:
int fd = open(file_name, O_RDWR | O_APPEND | O_CREAT);
but it fails (** fd = -1 with Error: permission denied**) when the file already exists. I am using the access() function to see if the file already exists:
if (access(file_name, F_OK) != -1)
{
printf("file %s already exists! \n", file_name);
remove(file_name); /* delete the existing file */
fd = open(file_name, O_RDWR | O_APPEND | O_CREAT);
}
Is there a better way to use the open() function to get a file descriptor for the following two scenarios:
- if the file does not exist, create it and return a file descriptor
- if the file exists, delete it and create a new file, then return a file descriptor.
echo "hello" >hello.txt