Vladimír Fencák Vladimír Fencák - 1 month ago 9
C Question

octal string to integer for open(O_CREATE) permissions

How to use an octal string from *argv[] for something like:

open("outfile",O_CREAT | O_RDWR,0777);


0777 means permission in octal numbers.

My code:

int arC = atoi(argv[optind]);
printf("argv optind %s after atoi %d\n",argv[optind],arC);
int test =des2=open("createfile",O_CREAT | O_RDWR,arC);
printf("fd %d\n",test);


Terminal output:

./copymaster -c 0777 in
argv optind 0777 after atoi 777
fd 5


But permissions are not set to 0777.
open()
just ignores
arC
.

How to convert this string
argv[optind]
to a usable form for the
open()
command?

Answer

atoi converts a string to integer when the string contains the integer in decimal representation.

But in your case the number is given in octal representation, so you cannot use atoi.

The strtol function is more general, because you can specify the base (8 in your case).

Replace

int arC = atoi(argv[optind]);    // convert decimal number

by

int arC = strtol(argv[optind], NULL, 8);   // convert octal number

With this modification your program would print this:

./copymaster -c 0777 in 
argv optind 0777 after strtol 511
...

511 being 0777 octal converted to decimal.

Comments