英文:
A file is populated with data on Windows but not on Linux
问题
我做了一个小的服务应用程序,它将输出写入多个文件。该服务必须在Windows和Linux上运行。在Windows上一切正常,但在Linux上,文件被创建了,但都是空的。
下面的小程序展示了完全相同的行为:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
f, err := os.OpenFile("test.txt", os.O_APPEND|os.O_CREATE, 0777)
if err != nil {
fmt.Println(err.Error())
return
}
defer f.Close()
w := bufio.NewWriter(f)
_, err = w.Write([]byte("hello"))
if err != nil {
fmt.Println(err.Error())
}
w.Flush()
}
当运行上述代码时,在Linux上似乎没有输出任何错误。通过test.txt的文件大小可以看出,在Windows上它确实将内容写入文件,而在Linux上则没有写入。
Windows上的目录:
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 14.04.2016 10:37 345 main.go
-a---- 14.04.2016 10:45 10 test.txt
-a---- 14.04.2016 10:37 2635264 writetest.exe
Linux上的目录:
drwxrwxr-x 2 localuser localuser 4096 Apr 14 10:55 ./
drwxr-xr-x 8 localuser localuser 4096 Apr 14 10:27 ../
-rw-rw-r-- 1 localuser localuser 345 Apr 14 10:37 main.go
-rwxrwxr-x 1 localuser localuser 0 Apr 14 10:55 test.txt*
我在这里漏掉了什么?
英文:
I have made a small service application that writes it's output to several files. The service has to run on both Windows and Linux. Everything is hunky-dory on Windows, but on Linux the files get created, but are all empty.
The following small program shows exactly the same behaviour:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
f, err := os.OpenFile("test.txt", os.O_APPEND|os.O_CREATE, 0777)
if err != nil {
fmt.Println(err.Error())
return
}
defer f.Close()
w := bufio.NewWriter(f)
_, err = w.Write([]byte("hello"))
if err != nil {
fmt.Println(err.Error())
}
w.Flush()
}
When run, the above code does not seem to output any errors on Linux. As can be seen by the file size of test.txt, it does write content to the file on Windows, while it does not do so on Linux.
Directory on Windows:
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 14.04.2016 10:37 345 main.go
-a---- 14.04.2016 10:45 10 test.txt
-a---- 14.04.2016 10:37 2635264 writetest.exe
Directory on Linux:
drwxrwxr-x 2 localuser localuser 4096 Apr 14 10:55 ./
drwxr-xr-x 8 localuser localuser 4096 Apr 14 10:27 ../
-rw-rw-r-- 1 localuser localuser 345 Apr 14 10:37 main.go
-rwxrwxr-x 1 localuser localuser 0 Apr 14 10:55 test.txt*
What am I missing here?
答案1
得分: 3
将你的标志从os.O_APPEND|os.O_CREATE
更改为os.O_RDWR|os.O_APPEND|os.O_CREATE
将在Linux和Mac OSX上起作用。
关键思想是,即使你想要追加文件,你在Linux和Mac OSX上仍然需要用写入标志打开。
英文:
Change your flag, from os.O_APPEND|os.O_CREATE
to os.O_RDWR|os.O_APPEND|os.O_CREATE
will work on Linux and Mac OSX.
The key idea is event you want to append the file, you still need to open with Write flag in Linux and Mac OSX.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论