'Permission Denied when trying to use open() with POSIX commands in C++

I currently have this code where I need to use standard POSIX calls to write text to a file:

file = open(filename, O_CREAT | O_RDWR | O_APPEND, S_IRUSR | S_IWUSR);
   if (file == -1) {
        perror("File cannot be opened");
        return -1;
    }

However, every time I run it, I get the permission denied error: File cannot be opened: Permission denied

I tried finding something online and found this "Permission denied" in open() function in C but when trying those suggestions, I get the same issue and idk if it's because I am using C++ while they were using C. For reference, I am on a Mac and am running this through an IDE (CLion)

please help!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source