Fprintf not writing to file

1,050 views
Skip to first unread message

gocss

unread,
Jul 17, 2011, 9:47:49 PM7/17/11
to golang-nuts
I have a test.dat file that is zero length
ls -ltr test.dat
-rwxrwxrwx 1 cssadmin cssadmin 0 2011-07-17 21:40 test.dat

I would expect the following code to append 'lineA' to the file,
but it does not error and checking the 'test.dat' file has NOTHING
added.
Executing the code outputs: n: 6

What am I overlooking?


1 package main
2
3 import (
4 "bufio"
5 "fmt"
6 "os"
7 )
8
9 func main() {
10 file, err := os.OpenFile("test.dat", os.O_APPEND, 0777)
11 if err != nil {
12 fmt.Println("err0")
13 os.Exit(1)
14 }
15 defer file.Close()
16 n, e := fmt.Fprintf(bufio.NewWriter(file), "%s\n", "lineA")
17 if e != nil {
18 fmt.Println("e:", e)
19 os.Exit(2)
20 }
21 fmt.Println("n:", n)
22 }

Jessta

unread,
Jul 17, 2011, 10:22:35 PM7/17/11
to gocss, golang-nuts
On Mon, Jul 18, 2011 at 11:47 AM, gocss <g...@curtissystemssoftware.com> wrote:
>  9 func main() {
>  10   file, err := os.OpenFile("test.dat", os.O_APPEND, 0777)
>  11   if err != nil {
>  12     fmt.Println("err0")
>  13     os.Exit(1)
>  14   }
>  15   defer file.Close()
>  16   n, e := fmt.Fprintf(bufio.NewWriter(file), "%s\n", "lineA")

bufio.Writer provides buffered writes. The default buffer size is 4096 bytes.
So an bufio.Writer won't write the the io.Writer (the file) until 4096
bytes has been written to it.
You don't need the bufio.Writer here, the file itself will work fine.

If you want a bufio.Writer to write out it's buffer call the Flush()
method on it.


>  17   if e != nil {
>  18     fmt.Println("e:", e)
>  19     os.Exit(2)
>  20   }
>  21   fmt.Println("n:", n)
>  22 }
>

--
=====================
http://jessta.id.au

Jan Mercl

unread,
Jul 18, 2011, 5:42:50 AM7/18/11
to golan...@googlegroups.com
I think os.O_APPEND is not enough flags for os.OpenFile (missing R/W mode). The code bellow seems to work:

package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
)

func main() {
    f, err := os.OpenFile("test.dat", os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()

    b := bufio.NewWriter(f)
    defer func() {
        if err = b.Flush(); err != nil {
            log.Fatal(err)
        }
    }()

    n, err := fmt.Fprintf(b, "%s\n", "lineA")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("n:", n)
}

Reply all
Reply to author
Forward
0 new messages