github.com/v2fly/v2ray-core/v4@v4.45.2/common/platform/filesystem/file.go (about)

     1  package filesystem
     2  
     3  import (
     4  	"io"
     5  	"os"
     6  
     7  	"github.com/v2fly/v2ray-core/v4/common/buf"
     8  	"github.com/v2fly/v2ray-core/v4/common/platform"
     9  )
    10  
    11  type FileSeekerFunc func(path string) (io.ReadSeekCloser, error)
    12  
    13  type FileReaderFunc func(path string) (io.ReadCloser, error)
    14  
    15  type FileWriterFunc func(path string) (io.WriteCloser, error)
    16  
    17  var NewFileSeeker FileSeekerFunc = func(path string) (io.ReadSeekCloser, error) {
    18  	return os.Open(path)
    19  }
    20  
    21  var NewFileReader FileReaderFunc = func(path string) (io.ReadCloser, error) {
    22  	return os.Open(path)
    23  }
    24  
    25  var NewFileWriter FileWriterFunc = func(path string) (io.WriteCloser, error) {
    26  	return os.Create(path)
    27  }
    28  
    29  func ReadFile(path string) ([]byte, error) {
    30  	reader, err := NewFileReader(path)
    31  	if err != nil {
    32  		return nil, err
    33  	}
    34  	defer reader.Close()
    35  
    36  	return buf.ReadAllToBytes(reader)
    37  }
    38  
    39  func WriteFile(path string, payload []byte) error {
    40  	writer, err := NewFileWriter(path)
    41  	if err != nil {
    42  		return err
    43  	}
    44  	defer writer.Close()
    45  
    46  	return buf.WriteAllBytes(writer, payload)
    47  }
    48  
    49  func ReadAsset(file string) ([]byte, error) {
    50  	return ReadFile(platform.GetAssetLocation(file))
    51  }
    52  
    53  func CopyFile(dst string, src string) error {
    54  	bytes, err := ReadFile(src)
    55  	if err != nil {
    56  		return err
    57  	}
    58  	f, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY, 0o644)
    59  	if err != nil {
    60  		return err
    61  	}
    62  	defer f.Close()
    63  
    64  	_, err = f.Write(bytes)
    65  	return err
    66  }