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

huangapple go评论84阅读模式
英文:

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

问题

考虑以下在Golang中的简短程序,它尝试写入一个文件。

package main

import "io/ioutil"
import "os"

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

运行该程序后,我得到了一个具有以下权限的文件。

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

这些权限基本上是无法使用的。

如果我运行等效的C程序。

#include <stdio.h>

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

那么我得到的文件看起来像这样,这更加理想。

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

Golang程序中,正确的标志组合是什么,以产生与C程序相同权限的文件?

我查看了FileMode文档,但没有找到合适的候选项。

英文:

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

package main

import &quot;io/ioutil&quot;
import &quot;os&quot;

func main() {
    ioutil.WriteFile(&quot;/tmp/FooBar&quot;, []byte(&quot;Hello World&quot;), 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 &lt;stdio.h&gt;

int main(){
    FILE* foo = fopen(&quot;/tmp/BarFoo&quot;, &quot;a&quot;);
    fprintf(foo, &quot;Hello World&quot;);
    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.

答案1

得分: 4

FileMode包括了新创建文件的权限位,因此你需要提供这些权限位:

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

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

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

huangapple
  • 本文由 发表于 2015年10月13日 06:14:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/33091071.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定