Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a numeric string starting with 0 to an octal number

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?

like image 431
Eduardo Ramos Avatar asked Mar 10 '23 08:03

Eduardo Ramos


1 Answers

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);
like image 182
dbush Avatar answered Mar 23 '23 00:03

dbush