I’m working on a program that needs to store some information and I’ve decided to use a simple file for it.
When the program starts it executes the following code, which should result in a file opened in append mode if it exists, or created if it doesn’t (The first time the program loads it should create it in the next times it just have 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 doesn’t exists, it’s created successfully and the program runs OK. But when the file already exist, it says “Permission denied” even though it’s the same program under the same user that created the file.
Some more details:
- I’m using Ubuntu 12.04 LTS
- When I check using “ls -l” the permissions on the file are: “–w–wx-wT”
- chmod-ing from the terminal with 666 solves to issue
- chmod()-ing in the code didn’t help at all
Thanks!
Advertisement
Answer
As per the man page of open()
, (some of) the required values for mode
field are
S_IRWXU
00700 user (file owner) has read, write and execute permission
S_IRUSR
00400 user has read permission S_IWUSR 00200 user has write permission
S_IXUSR
00100 user has execute permission
and so on.
So, we can clearly see, the notation is octal. You need to use 0666
to denote octal notation.