I am trying to do this:
void main(int argc, char *argv[]){
int mode,f;
mode = atoi(argv[2]);
if((f = open("fichero.txt",O_CREAT, mode))==-1){
perror("Error");
exit(1);
}
}
However, when I introduce a number like 0664, mode equals 664. How can I keep that leading zero?
The atoi
function assumes the string is the decimal representation of a number. If you want to convert from different bases, use strtol
.
mode = strtol(argv[2], NULL, 0);
The third argument specifies the number base. If this value is 0, it will treat the string as hexadecimal if it starts with 0x
, octal if it starts with 0
, and decimal otherwise.
If you expect the string to always be the octal representation, then set the base to 8.
mode = strtol(argv[2], NULL, 8);
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