How to convert a numeric string, starting from 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 entered a number like 0664, the mode is 664. How can I keep this leading zero?

+4
source share
1 answer

The function atoiassumes that the string is a decimal representation of a number. If you want to convert from different databases, use strtol.

mode = strtol(argv[2], NULL, 0);

The third argument indicates the base number. 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.

, , 8.

mode = strtol(argv[2], NULL, 8);
+7

Source: https://habr.com/ru/post/1664476/


All Articles