github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/common/platform/filesystem/file.go (about)

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