I am trying out this code below.
printf("enter the file name\n");
printf("error opening file\n");
printf("file opened successfully\n");
Here,I am settings file's permission such that only user can read this. When i execute this code for the first time it works as expected.But for the second time it shows the error message.My doubt is that why it is giving error message as I have already set the required permission mode in sync with flag modes.
Best How To :
The problem is the particular combination of open flags. What you are saying is:
- Create this file it it doesn't exist (
- Truncate it (
- Set its permissions to 0400 (
The next time around when you try to open it, since it already exists
open will just try to truncate it. Truncating however will fail since you only have read permissions on the file.
An easy way to fix this would be to specify more inclusive permissions, i.e.
An easy way to diagnose this, and a good practice generally, would be to check
errno after the system call fails. (
perror, for example, will give a human-readable error message.) You would have seen the call fail with EACCES, which is documented as arising when "O_TRUNC is specified and write permission is denied.".