Last active
January 6, 2017 07:58
-
-
Save princebot/eb85e8c87552e184370abf13fb793d38 to your computer and use it in GitHub Desktop.
General difference between `stat` and `open` for files.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This demonstrates a little bit of how Unix directories work, re late-night chat with Bujol about Facebook Haystack. | |
// | |
// (Go makes this clearer than languages like Python or Ruby generally do.) | |
package main | |
import ( | |
"bytes" | |
"fmt" | |
"go/doc" | |
"log" | |
"os" | |
) | |
var cwd string // current working directory | |
func init() { | |
var err error | |
if cwd, err = os.Getwd(); err != nil { | |
log.Fatal(err) | |
} | |
} | |
func main() { | |
// Getting file info doesn't really require opening the file. | |
fi, err := os.Stat(cwd) | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Print(format(fi)) | |
// However, if you want to read contents, you have to open the file — | |
// and a directory’s contents happen to be its file list. | |
dir, err := os.Open(cwd) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer dir.Close() | |
files, err := dir.Readdirnames(-1) | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Printf("files in %s:\n", dir.Name()) | |
for _, f := range files { | |
log.Printf("\t%s\n", f) | |
} | |
} | |
// format is an absurdly unnecessary prettyprinter for FileInfo. | |
func format(fi os.FileInfo) string { | |
var b bytes.Buffer | |
fmt.Fprintf(&b, "file info for %s:\n", fi.Name()) | |
doc.ToText(&b, fmt.Sprintf("%#v", fi), "\t\t\t", "", 59) | |
b.WriteByte('\n') | |
return b.String() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment