Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening a File from a FileInfo

Tags:

In golang, if I have an os.FileInfo, is there any way to open an *os.File from that by itself without the original path?

Let's say I had something like this:

package main  import (     "os"     "path/filepath"     "strings" )  var files []os.FileInfo  func walker(path string, info os.FileInfo, err error) error {     if strings.HasSuffix(info.Name(), ".txt") {         files = append(files, info)     }     return nil }  func main() {     err := filepath.Walk("/tmp/foo", walker)     if err != nil {         println("Error", err)     } else {         for _, f := range files {             println(f.Name())             // This is where we'd like to open the file         }     } } 

Is there a way to convert FileInfo to * File? The code I'm actually working with isn't based on filepath.Walk; but I do get an []os.FileInfo slice back. I still have the root directory, and the file name, but it seems like any further sub-tree information has gone by this stage.

like image 467
Rich L Avatar asked May 04 '15 21:05

Rich L


People also ask

What is open () in C#?

Open(String, FileStreamOptions) Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, the access other FileStreams can have to the same file, the buffer size, additional file options and the allocation size.


2 Answers

No. The FileInfo interface simply does not expose the path and all provided methods in the os and ioutil packages accept the pathname as a string.

like image 55
evanmcdonnal Avatar answered Sep 23 '22 07:09

evanmcdonnal


As additional info, this is how to constructor the filename string including path:

filename := filepath.Join(path, info.Name()) 
like image 34
D-rk Avatar answered Sep 21 '22 07:09

D-rk