I have been trying to write some text to a file in OCaml and stumbled on the following problem.
Opening a channel with open_out_gen
allows to set permissions for a newly created file as well as mode with which the file is opened.
For example:
let write_to_file perm =
let oc = open_out_gen [Open_creat; Open_append] perm ((Int.to_string perm )^".txt") in
Printf.fprintf oc "%s\n" "yolo";
close_out oc;;
opens a channel for a file named <perm>.txt and appends "yolo" at the end of it.
A problem appears when I check the permission of the newly created file. Intuitively I would assume that the permission flag shown by ls -l
will be equal to the value of perm
. By that I mean, if I invoke the above function with write_to_file 777
the new file should have rwx flags for the owner, group and others.
But when I check its permissions it shows "-r----x--t" so the file can be read by owner, executed by everyone in the owner's group and it can be deleted only by the owner of the file.
My question is why is it the result and how can I actually give the permissions like rwx for everyone?
You're using 777
for the permissions, which is a base-10 number. In the base-8 notation usually used for numeric file permissions, that would be 1411
, which corresponds to the symbolic permissions you describe - sticky bit, user readable, group and other executable (The other executable bit isn't shown by ls -l
because of the sticky bit's t
but it's there).
In ocaml, base-8 literals are prefixed by 0o
, so write_to_file 0o777
will give you the permissions you want.