merlin2011
merlin2011

Reputation: 75629

Which combination of os.FileMode's corresponds to `a` in fopen, with respect to the permissions on the created file?

Consider the following short program in Golang, which simply attempts to write a file.

package main

import "io/ioutil"
import "os"

func main() {
    ioutil.WriteFile("/tmp/FooBar", []byte("Hello World"), os.ModeAppend)
}

After running this program, I get a file with the following permissions.

---------- 1 merlin sudo 5 Oct 12 15:02 /tmp/FooBar

The permissions are essentially unuseable.

If I run the equivalent C program.

#include <stdio.h>

int main(){
    FILE* foo = fopen("/tmp/BarFoo", "a");
    fprintf(foo, "Hello World");
    fclose(foo);
}

Then I get a file that looks like this, which is much more desirable.

-rw-r--r-- 1 merlin sudo 11 Oct 12 15:10 /tmp/BarFoo

What is the correct combination of flags in the Golang program to produce a file with the same permissions as the C program?

I have looked at the FileMode documentation but did not see any good candidates.

Upvotes: 1

Views: 859

Answers (1)

Ry-
Ry-

Reputation: 225164

As FileMode includes permission bits for newly-created files, you’ll need to provide those:

ioutil.WriteFile("/tmp/FooBar", []byte("Hello World"), os.ModeAppend | 0644)

Upvotes: 4

Related Questions