tags:

views:

614

answers:

4

I've been trying to learn Go / Golang on my own, but I've been stumped on trying read and write to ordinary files.

I can get as far as: inFile,_ := os.Open(INFILE,0,0);

but actually getting the content of the file doesn't make sense, since the read function takes a []byte as a parameter??

func (file *File) Read(b []byte) (n int, err Error)
A: 

Just looking at the documentation it seems you should just declare a buffer of type []byte and pass it to read which will then read up to that many characters and return the number of characters actually read (and an error).

The docs say

Read reads up to len(b) bytes from the File. It returns the number of bytes read and an Error, if any. EOF is signaled by a zero count with err set to EOF.

Does that not work?

EDIT: Also, I think you should perhaps use the Reader/Writer interfaces declared in the bufio package instead of using os package.

kigurai
+4  A: 

Try this:

package main

import (
  "io"; 
  )


func main() {
  contents,_ := io.ReadFile("filename");
  println(string(contents));
  io.WriteFile("filename", contents, 0x644);
}
marketer
This will work if you want to read the whole file at once. If the file's really big or you only want to read part of it, it might not be what you're looking for.
Evan Shaw
You should really check the error code, and not ignore it like that!!
hasen j
This has been moved into the ioutil package now. So it would be ioutil.ReadFile()
Christopher
+5  A: 

[]byte is a slice (similar to a substring) of all or part of a byte array. Think of the slice as a value structure with a hidden pointer field for the system to locate and access all or part of an array (the slice), plus fields for the length and capacity of the slice, which you can access using the len() and cap() functions.

Here's a working starter kit for you, which reads and prints a binary file; you will need to change the inName literal value to refer to a small file on your system.

package main
import (
    "fmt";
    "os";
)
func main()
{
    inName := "file-rw.bin";
    inPerm :=  0666;
    inFile, inErr := os.Open(inName, os.O_RDONLY, inPerm);
    if inErr == nil {
     inBufLen := 16;
     inBuf := make([]byte, inBufLen);
     n, inErr := inFile.Read(inBuf);
     for inErr == nil {
      fmt.Println(n, inBuf[0:n]);
      n, inErr = inFile.Read(inBuf);
     }
    }
    inErr = inFile.Close();
}
peterSO
The Go convention is to check for error first, and let the normal code reside outside the `if` block
hasen j
+1. `if error { return }`
Jurily
@Jurily: If the file is open when the error occurs, how do you close it?
peterSO
@peterSO: use defer
James Antill
A: 

This is good version:

package main

import (
  "io/ioutil"; 
  )


func main() {
  contents,_ := ioutil.ReadFile("plikTekstowy.txt")
  println(string(contents))
  ioutil.WriteFile("filename", contents, 0x777)
}

Piotr

Piotr