Permission denied in Linux when accessing a file I created with the same application

I am working on a program that needs to store some information and I decided to use a simple file for it.

When the program starts, it executes the following code, which should result in the file being opened in append mode if it exists, or created if not (The first time the program is loaded, it should create it the next time it just needs to use the same file)

if((fd = open(path, O_APPEND|O_CREAT|O_RDWR, 666)) < 0)
{
    perror("Database open failed");
}
else if(chmod(path, 666) < 0)
{
    perror("Database set permissions failed");
}
else if((stream = fdopen(fd, "a+")) == NULL)
{
    perror("Database get stream failed");
}

      

When the file does not exist, it is successfully created and the program runs fine. But when the file already exists, it says "Permission denied" even if it is the same program under the same user who created the file.

Additional Information:

  • I am using Ubuntu 12.04 LTS
  • When I check using "ls -l" the file permissions are: "--w - wx-wT"
  • chmod-ing from terminal with 666 release solutions
  • chmod () - the code in the code didn't help at all

Thank!

+3


source to share


2 answers


According to the man page open()

, (some of the) required values ​​for the field mode

are

S_IRWXU

User

00700 (file owner) has read, write and execute permissions

S_IRUSR

00400 user has read permission. User S_IWUSR 00200 has write permission.

S_IXUSR

00100 user has execute permission



etc.

So we can clearly see that the designation is octal. You must use 0666

octal to refer to.

+1


source


The mode for open()

must be octal, i.e. 666

should be 0666

.



Better to use symbolic constants for the mode.

+2


source







All Articles