I have a program where I need to set the permissions of a file (say /home/hello.t
) using chmod
and I have to read the permissions to be set from a file. For this I first read the permissions into a character array and then try to modify the permissions of the file. But I see that permissions are set in a weird manner.
A sample program I have written:
main()
{
char mode[4]="0777";
char buf[100]="/home/hello.t";
int i;
i = atoi(mode);
if (chmod (buf,i) < 0)
printf("error in chmod");
}
I see that the permissions of the file are not set to 777. Can you please help me out on how to set the permissions of the file after reading the same from a character array.
The
atoi()
function only translates decimal, not octal.For octal conversion, use
strtol()
(or, as Chris Jester-Young points out,strtoul()
- though the valid sizes of file permission modes for Unix all fit within 16 bits, and so will never produce a negativelong
anyway) with either 0 or 8 as the base. Actually, in this context, specifying 8 is best. It allows people to write 777 and get the correct octal value. With a base of 0 specified, the string 777 is decimal (again).Additionally:
main()
; be explicit as required by C99 and useint main(void)
orint main(int argc, char **argv)
.Do not play with chopping trailing nulls off your string.
This prevents C from storing a terminal null - bad! Use:
This allocates the 5 bytes needed to store the string with a null terminator.
Report errors on
stderr
, notstdout
.<string.h>
header (forstrerror()
) and<errno.h>
forerrno
. Additionally, the exit status of the program should indicate failure when thechmod()
operation fails.Putting all the changes together yields:
Be careful with
errno
; it can change when functions are called. It is safe enough here, but in many scenarios, it is a good idea to captureerrno
into a local variable and use the local variable in printing operations, etc.Note too that the code does no error checking on the result of
strtol()
. In this context, it is safe enough; if the user supplied the value, it would be a bad idea to trust them to get it right.One last comment: generally, you should not use 777 permission on files (or directories). For files, it means that you don't mind who gets to modify your executable program, or how. This is usually not the case; you do care (or should care) who modifies your programs. Generally, don't make data files executable at all; when files are executable, do not give public write access and look askance at group write access. For directories, public write permission means you do not mind who removes any of the files in the directory (or adds files). Again, occasionally, this may be the correct permission setting to use, but it is very seldom correct. (For directories, it is usually a good idea to use the 'sticky bit' too: 1777 permission is what is typically used on
/tmp
, for example - but not on MacOS X.)