file - 文件在 Windows 上填充了数据,但在 Linux 上没有

标签 file go buffer

我制作了一个小型服务应用程序,可以将其输出写入多个文件。该服务必须同时在 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*

我在这里错过了什么?

最佳答案

将标志从 os.O_APPEND|os.O_CREATE 更改为 os.O_RDWR|os.O_APPEND|os.O_CREATE 将在 Linux 和 Mac OSX 上运行。

关键思想是如果你想附加文件,你仍然需要在 Linux 和 Mac OSX 中使用 Write 标志打开。

关于file - 文件在 Windows 上填充了数据,但在 Linux 上没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36618329/

相关文章:

xml - 如何使用go检查XML文件中是否存在标签?

time - Go 中 time.Time 的 `zero` 值是多少?

c - 在 C 中打印长度为 char 的缓冲区

c - 我从 C - Linux 中的 .txt 文件中得到错误的输出

arrays - Windows 批处理静态列表重命名-移动

linux - 使用管道缩短 bash 脚本

window - 为 ascii 游戏生成一个窗口

c - 如何处理动态分配的 struct C 中的段错误

go - 如何在golang模板中的LOOP内执行IF/ELSE条件?

c++ - 无法使用 Winsock WSABUF 发送图像文件 (image/jpg)