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
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 negative long
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 use int main(void)
or int main(int argc, char **argv)
.Do not play with chopping trailing nulls off your string.
char mode[4] = "0777";
This prevents C from storing a terminal null - bad! Use:
char mode[] = "0777";
This allocates the 5 bytes needed to store the string with a null terminator.
Report errors on stderr
, not stdout
.
header (for strerror()
) and
for errno
. Additionally, the exit status of the program should indicate failure when the chmod()
operation fails.Putting all the changes together yields:
#include
#include
#include
#include
#include
int main(int argc, char **argv)
{
char mode[] = "0777";
char buf[100] = "/home/hello.t";
int i;
i = strtol(mode, 0, 8);
if (chmod (buf,i) < 0)
{
fprintf(stderr, "%s: error in chmod(%s, %s) - %d (%s)\n",
argv[0], buf, mode, errno, strerror(errno));
exit(1);
}
return(0);
}
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 capture errno
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.)