I'm trying to call the chmod() function from my C program, but it
isn't setting the correct permissions unless the mode_t argument has
leading zeroes in it. For example chmod(argv[2],00777) will work,
but chmod(argv[2],777) will set the permissions to complete garbage.
The big problem comes when I try to use atoi() because it will
discard any leading zeroes. Is there any way I can make the following
program work even if the user enters a value with no leading zeroes
in the command line?
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
if (argc != 3)
exit(EXIT_FAILURE);
if (chmod(argv[2], (mode_t)atoi(argv[1])) != 0)
printf("Warning: Unable to change file permissions.");
return 0;
}
Yes, the zero is necessary, unless you convert the number into the correct base ahead of time. A leading zero in an integer literal makes C read the number in octal, in the same way that 0x makes it read the integer in hexadecimal. If you use strtol, you can provide a base parameter of 8 to read an integer in octal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With