本文整理汇总了Golang中os.File.Sync方法的典型用法代码示例。如果您正苦于以下问题:Golang File.Sync方法的具体用法?Golang File.Sync怎么用?Golang File.Sync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os.File
的用法示例。
在下文中一共展示了File.Sync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
var tmp *os.File
var err os.Error
flag.Parse()
args := flag.Args()
if len(args) == 1 {
dir, _ := path.Split(args[0])
tmp, err = ioutil.TempFile(dir, "")
exitOnErr(err)
} else if len(args) == 2 {
tmp, err = os.Open(args[1], os.O_RDWR|os.O_CREAT, 0644)
exitOnErr(err)
} else {
usage()
}
fname := args[0]
tmpname := tmp.Name()
exitOnErr(cdb.Make(tmp, bufio.NewReader(os.Stdin)))
exitOnErr(tmp.Sync())
exitOnErr(tmp.Close())
exitOnErr(os.Rename(tmpname, fname))
}
示例2: CopyFileContents
// CopyFileContents copies the contents of the file named src to the file named
// by dst. The file will be created if it does not already exist. If the
// destination file exists, all it's contents will be replaced by the contents
// of the source file.
//
// From http://stackoverflow.com/a/21067803
func CopyFileContents(src, dst string) (err error) {
in, err := os.Open(src)
if err != nil {
return
}
defer in.Close()
ext := filepath.Ext(dst)
var out *os.File
if ext == ".sh" {
out, err = os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0766)
} else {
out, err = os.Create(dst)
}
if err != nil {
return
}
defer func() {
cerr := out.Close()
if err == nil {
err = cerr
}
}()
if _, err = io.Copy(out, in); err != nil {
return
}
err = out.Sync()
return
}
示例3: CopyAs
// CopyAs copies a file
func (fh *FileHandle) CopyAs(path string) (err error) {
var src, dst *os.File
// open src
if src, err = os.Open(fh.Path); err != nil {
return err
}
defer src.Close()
// open dest
if dst, err = os.Create(path); err != nil {
return err
}
defer func() {
closeErr := dst.Close()
if err == nil {
err = closeErr
if err == nil {
// copy success - update file name / path
fh.Name = filepath.Base(path)
fh.Path = path
}
}
}()
// copy
if _, err = io.Copy(dst, src); err != nil {
return
}
// sync
err = dst.Sync()
return
}
示例4: persistMetaData
// persistMetaData atomically writes state to the filesystem
func (d *DiskQueue) persistMetaData() error {
var f *os.File
var err error
d.metaMutex.Lock()
depth := d.depth
readFileNum := d.readFileNum
readPos := d.readPos
writeFileNum := d.writeFileNum
writePos := d.writePos
d.metaMutex.Unlock()
fileName := d.metaDataFileName()
tmpFileName := fileName + ".tmp"
// write to tmp file
f, err = os.OpenFile(tmpFileName, os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
return err
}
_, err = fmt.Fprintf(f, "%d\n%d,%d\n%d,%d\n",
depth,
readFileNum, readPos,
writeFileNum, writePos)
if err != nil {
f.Close()
return err
}
f.Sync()
f.Close()
// atomically rename
return os.Rename(tmpFileName, fileName)
}
示例5: CreateFile
func CreateFile(name string) (flvFile *File, err error) {
var file *os.File
// Create file
if file, err = os.Create(name); err != nil {
return
}
// Write flv header
if _, err = file.Write(HEADER_BYTES); err != nil {
file.Close()
return
}
// Sync to disk
if err = file.Sync(); err != nil {
file.Close()
return
}
flvFile = &File{
file: file,
name: name,
readOnly: false,
headerBuf: make([]byte, 11),
duration: 0.0,
}
return
}
示例6: mapPairToCSV
func mapPairToCSV(colHeader string, inMap PairList, fh *os.File, geo *geoip.GeoIP) int {
nb, err := fh.WriteString(colHeader + "\n")
check(err)
totalBytes := nb
i := 0
for _, v1 := range inMap {
matches := regexp.MustCompile(`([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)`).FindStringSubmatch(v1.Key)
if len(matches) >= 1 && geo != nil {
record := geo.GetRecord(v1.Key)
if record != nil {
nb, err = fh.WriteString(v1.Key + csvd + strconv.Itoa(v1.Value) + csvd + record.City + csvd + record.CountryName + "\n")
}
} else {
nb, err = fh.WriteString(v1.Key + csvd + strconv.Itoa(v1.Value) + "\n")
}
check(err)
totalBytes += nb
i++
}
fh.Sync()
return totalBytes
}
示例7: handle
func (d *Daemon) handle(input link.Input, process *os.Process, stdin *os.File) error {
if input.WindowSize != nil {
setWinSize(stdin, input.WindowSize.Columns, input.WindowSize.Rows)
process.Signal(syscall.SIGWINCH)
} else if input.EOF {
stdin.Sync()
err := stdin.Close()
if d.WithTty {
process.Signal(syscall.SIGHUP)
}
if err != nil {
return err
}
} else if input.Signal != nil {
if input.Signal.Signal == garden.SignalTerminate {
process.Signal(syscall.SIGTERM)
} else if input.Signal.Signal == garden.SignalKill {
process.Signal(syscall.SIGKILL)
}
} else {
_, err := stdin.Write(input.StdinData)
if err != nil {
return err
}
}
return nil
}
示例8: processLinkRequests
// Loop receiving and processing link requests on the given connection.
// The loop terminates when the connection is closed or an error occurs.
func processLinkRequests(conn net.Conn, stdinW *os.File, cmd *exec.Cmd, withTty bool) {
decoder := gob.NewDecoder(conn)
for {
var input linkpkg.Input
err := decoder.Decode(&input)
if err != nil {
break
}
if input.WindowSize != nil {
setWinSize(stdinW, input.WindowSize.Columns, input.WindowSize.Rows)
cmd.Process.Signal(syscall.SIGWINCH)
} else if input.EOF {
stdinW.Sync()
err := stdinW.Close()
if withTty {
cmd.Process.Signal(syscall.SIGHUP)
}
if err != nil {
conn.Close()
break
}
} else {
_, err := stdinW.Write(input.Data)
if err != nil {
conn.Close()
break
}
}
}
}
示例9: DumpStacks
// DumpStacks appends the runtime stack into file in dir and returns full path
// to that file.
func DumpStacks(dir string) (string, error) {
var (
buf []byte
stackSize int
)
bufferLen := 16384
for stackSize == len(buf) {
buf = make([]byte, bufferLen)
stackSize = runtime.Stack(buf, true)
bufferLen *= 2
}
buf = buf[:stackSize]
var f *os.File
if dir != "" {
path := filepath.Join(dir, fmt.Sprintf(stacksLogNameTemplate, strings.Replace(time.Now().Format(time.RFC3339), ":", "", -1)))
var err error
f, err = os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
return "", errors.Wrap(err, "failed to open file to write the goroutine stacks")
}
defer f.Close()
defer f.Sync()
} else {
f = os.Stderr
}
if _, err := f.Write(buf); err != nil {
return "", errors.Wrap(err, "failed to write goroutine stacks")
}
return f.Name(), nil
}
示例10: WriteConfigFile
// WriteConfigFile wirtes a valid nginx config to f
// Proxies are indicated in routes
// Other configuration specified in config
func WriteConfigFile(f *os.File, routes map[string]int, config Config) {
var routesBuffer bytes.Buffer
for path, port := range routes {
locationStr := "\t\tlocation /%s {\n\t\t\treturn 302 /%s/;\n\t\t}\n\n\t\tlocation /%s/ {\n\t\t\tproxy_pass http://127.0.0.1:%d/;\n\t\t}\n"
fmt.Fprintf(&routesBuffer, locationStr, path, path, path, port)
}
serverName := config.ServerName
if serverName == "" {
serverName = "localhost"
}
var rootRule string
defaultPort := config.DefaultPort
if defaultPort == 0 {
rootRule = "return 404;"
} else {
rootRule = "proxy_pass http://127.0.0.1:" + strconv.Itoa(defaultPort) + ";"
}
fmt.Fprintf(f, configText, serverName, routesBuffer.String(), rootRule)
err := f.Sync()
if err != nil {
log.Fatal("Error saving config file: ", err)
}
}
示例11: readUCHAR8
func readUCHAR8(file *os.File, s int64) ([]byte, int64) {
buf := make([]byte, s)
ntotal := int64(0)
for {
// read several times because Read might decide to stop intermittently
buffer := make([]byte, int64(1024)*int64(1024)) // read a little bit
n, err := file.Read(buffer)
if ntotal+int64(n) > s {
n = int(s - ntotal)
}
// copy to the real buffer buf
copy(buf[ntotal:(ntotal+int64(n))], buffer[0:n])
ntotal = ntotal + int64(n)
if err == io.EOF {
break
}
if err != nil {
panic(err)
}
}
file.Sync()
return buf, ntotal
}
示例12: Write
func Write(fn, str string, append bool) error {
var (
file *os.File
err error
)
if append {
file, err = os.OpenFile(fn, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.FileMode(0666))
} else {
file, err = os.OpenFile(fn, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, os.FileMode(0666))
}
defer file.Close()
if err != nil {
return err
}
_, err = file.WriteString(str)
if err != nil {
return err
}
file.Sync()
return nil
}
示例13: Generate_d5sFile
func Generate_d5sFile(file string, d5sConf *D5ServConf) (e error) {
var f *os.File
if file == NULL {
f = os.Stdout
} else {
f, e = os.OpenFile(file, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0600)
ThrowErr(e)
e = f.Truncate(0)
ThrowErr(e)
defer func() {
f.Sync()
f.Close()
}()
}
if d5sConf == nil {
d5sConf = new(D5ServConf)
d5sConf.RSAKeys = GenerateRSAKeyPair()
}
desc := getImportableDesc(d5sConf)
f.WriteString("#\n# deblocus server configuration\n#\n\n")
for k, d := range desc {
defaultVal := d.sType.Tag.Get("importable")
f.WriteString(fmt.Sprintf("%-16s %s\n", k, defaultVal))
}
f.WriteString("\n### Please take good care of this secret file during the server life cycle.\n")
f.WriteString("### DON'T modify the following lines, unless you known what happens.\n\n")
k := d5sConf.RSAKeys
keyBytes := x509.MarshalPKCS1PrivateKey(k.priv)
keyText := pem.EncodeToMemory(&pem.Block{
Type: SER_KEY_TYPE,
Bytes: keyBytes,
})
f.Write(keyText)
return
}
示例14: ensureSlot
func ensureSlot(item string) {
var err error
var fi *os.File
slot, err := filepath.Glob(Slots)
if err != nil {
panic(err)
}
fi, err = os.OpenFile(fmt.Sprintf("%v/slots", slot[0]), os.O_RDWR|os.O_APPEND, 0666)
if err != nil {
panic(err)
}
defer fi.Close()
// ensure the slot is not already written into the capemanager
// (from: https://github.com/mrmorphic/hwio/blob/master/module_bb_pwm.go#L190)
scanner := bufio.NewScanner(fi)
for scanner.Scan() {
line := scanner.Text()
if strings.Index(line, item) > 0 {
return
}
}
fi.WriteString(item)
fi.Sync()
scanner = bufio.NewScanner(fi)
for scanner.Scan() {
line := scanner.Text()
if strings.Index(line, item) > 0 {
return
}
}
}
示例15: persistMetaData
// persistMetaData atomically writes state to the filesystem
func (d *diskQueue) persistMetaData() error {
var f *os.File
var err error
fileName := d.metaDataFileName()
tmpFileName := fmt.Sprintf("%s.%d.tmp", fileName, rand.Int())
// write to tmp file
f, err = os.OpenFile(tmpFileName, os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
return err
}
_, err = fmt.Fprintf(f, "%d\n%d,%d\n%d,%d\n",
atomic.LoadInt64(&d.depth),
d.readFileNum, d.readPos,
d.writeFileNum, d.writePos)
if err != nil {
f.Close()
return err
}
f.Sync()
f.Close()
// atomically rename
return atomicRename(tmpFileName, fileName)
}