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

1.1k views Asked by At

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?

1

There are 1 answers

4
dbush On BEST ANSWER

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);