github.com/turingchain2020/turingchain@v1.1.21/cmd/tools/util/io.go (about)

     1  // Copyright Turing Corp. 2018 All Rights Reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package util
     6  
     7  import (
     8  	"bufio"
     9  	"fmt"
    10  	"io"
    11  	"io/ioutil"
    12  	"os"
    13  )
    14  
    15  //ReadFile : read file
    16  func ReadFile(file string) ([]byte, error) {
    17  	fileCont, err := ioutil.ReadFile(file)
    18  	if err != nil {
    19  		return nil, fmt.Errorf("Could not read file %s, err %s", file, err)
    20  	}
    21  
    22  	return fileCont, nil
    23  }
    24  
    25  //CheckFileIsExist : check whether the file exists or not
    26  func CheckFileIsExist(filename string) bool {
    27  	var exist = true
    28  	if _, err := os.Stat(filename); os.IsNotExist(err) {
    29  		exist = false
    30  	}
    31  	return exist
    32  }
    33  
    34  //WriteStringToFile : write content to file
    35  func WriteStringToFile(file, content string) (writeLen int, err error) {
    36  	var f *os.File
    37  	if err = MakeDir(file); err != nil {
    38  		return
    39  	}
    40  	DeleteFile(file)
    41  	if CheckFileIsExist(file) {
    42  		f, err = os.OpenFile(file, os.O_APPEND, 0666)
    43  	} else {
    44  		f, err = os.Create(file)
    45  	}
    46  	if err != nil {
    47  		return
    48  	}
    49  	defer f.Close()
    50  	w := bufio.NewWriter(f)
    51  	writeLen, err = w.WriteString(content)
    52  	w.Flush()
    53  	return
    54  }
    55  
    56  //CopyFile : copy file
    57  func CopyFile(srcFile, dstFile string) (written int64, err error) {
    58  	src, err := os.Open(srcFile)
    59  	if err != nil {
    60  		return
    61  	}
    62  	defer src.Close()
    63  	dst, err := os.OpenFile(dstFile, os.O_WRONLY|os.O_CREATE, 0644)
    64  	if err != nil {
    65  		return
    66  	}
    67  	defer dst.Close()
    68  	return io.Copy(dst, src)
    69  }