本文整理汇总了Golang中os.File.Write方法的典型用法代码示例。如果您正苦于以下问题:Golang File.Write方法的具体用法?Golang File.Write怎么用?Golang File.Write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os.File
的用法示例。
在下文中一共展示了File.Write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestSizeFileAndNestedDirectoryNonempty
// Test directory with 1 file and 1 non-empty directory
func TestSizeFileAndNestedDirectoryNonempty(t *testing.T) {
var err error
if err = os.MkdirAll("/tmp/testSizeFileAndNestedDirectoryEmpty/nested", 0777); err != nil {
t.Fatalf("failed to create directory: %s", err)
}
var file *os.File
if file, err = os.Create("/tmp/testSizeFileAndNestedDirectoryEmpty/file"); err != nil {
t.Fatalf("failed to create file: %s", err)
}
data := []byte{100, 111, 99, 107, 101, 114}
file.Write(data)
var nestedFile *os.File
if nestedFile, err = os.Create("/tmp/testSizeFileAndNestedDirectoryEmpty/nested/file"); err != nil {
t.Fatalf("failed to create file: %s", err)
}
nestedData := []byte{100, 111, 99, 107, 101, 114}
nestedFile.Write(nestedData)
var size int64
if size, _ = Size("/tmp/testSizeFileAndNestedDirectoryEmpty"); size != 12 {
t.Fatalf("directory with 6-byte file and empty directory has size: %d", size)
}
}
示例2: webrootWriteChallenge
// Tries to write a challenge file to each of the directories.
func webrootWriteChallenge(webroots map[string]struct{}, token string, ka []byte) {
log.Debugf("writing %d webroot challenge files", len(webroots))
for wr := range webroots {
os.MkdirAll(wr, 0755) // ignore errors
fn := filepath.Join(wr, token)
log.Debugf("writing webroot file %s", fn)
// Because /var/run/acme/acme-challenge may not exist due to /var/run
// possibly being a tmpfs, and because that tmpfs is likely to be world
// writable, there is a risk of following a maliciously crafted symlink to
// cause a file to be overwritten as root. Open the file using a
// no-symlinks flag if the OS supports it, but only for /var/run paths; we
// want to support symlinks for other paths, which are presumably properly
// controlled.
//
// Unfortunately earlier components in the pathname will still be followed
// if they are symlinks, but it looks like this is the best we can do.
var f *os.File
var err error
if strings.HasPrefix(wr, "/var/run/") {
f, err = deos.OpenFileNoSymlinks(fn, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
} else {
f, err = os.OpenFile(fn, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
}
if err != nil {
log.Infoe(err, "failed to open webroot file ", fn)
continue
}
f.Write(ka)
f.Close()
}
}
示例3: Lock
// Lock creates a lockfile which prevents to open more than one instance
// of the same node (on the same machine).
func (ctx *Context) Lock() (err error) {
var f *os.File
var p *os.Process
var pid int
lockFile := path.Join(ctx.storageDir, ctx.nodeName+".lock")
if f, err = os.Open(lockFile); err != nil {
goto lock
}
if _, err = fmt.Fscanf(f, "%d", &pid); err != nil && pid == 0 {
goto lock
}
if p, err = os.FindProcess(pid); err == nil && p != nil {
if err = p.Signal(os.UnixSignal(0)); err == nil {
return errors.New(
fmt.Sprintf("node '%s' is already running",
ctx.NodeName()))
}
}
lock:
// Write a lock file.
if f, err = os.Create(lockFile); err == nil {
pid := os.Getppid()
f.Write([]byte(fmt.Sprintf("%d", pid)))
f.Close()
}
return nil
}
示例4: assertAst
func assertAst(t *testing.T, root ast.Node, case_name string) {
var out []byte
var err error
if out, err = json.Marshal(root); err != nil {
t.Fatal(err)
}
var buf bytes.Buffer
if err = json.Indent(&buf, out, "", "\t"); err != nil {
t.Fatal(err)
}
var file *os.File
jsn := buf.String()
if file, err = os.Open(kTestingPrefix + case_name + ".json"); err != nil {
t.Logf("[%s] not found: %v, now dump: \n%s", case_name, err, jsn)
if file, err = os.Create(kTestingPrefix + case_name + ".json_"); err != nil {
panic(err)
}
file.Write(buf.Bytes())
file.Close()
return
}
defer file.Close()
buf.Reset()
if _, err = buf.ReadFrom(file); err != nil {
t.Fatal(err)
}
if buf.String() != jsn {
t.Fatalf("[%s] Assert failed, Expected: ----------\n%s\nValue is: ----------\n%s",
case_name, buf.String(), jsn)
}
}
示例5: GetPass
// GetPass reads password from a TTY with no echo.
func GetPass(prompt string, f *os.File, pbuf []byte) ([]byte, error) {
t, err := Attr(f)
if err != nil {
return nil, err
}
defer t.Set(f)
noecho := t
noecho.Lflag = noecho.Lflag &^ ECHO
if err := noecho.Set(f); err != nil {
return nil, err
}
b := make([]byte, 1, 1)
i := 0
if _, err := f.Write([]byte(prompt)); err != nil {
return nil, err
}
for ; i < len(pbuf); i++ {
if _, err := f.Read(b); err != nil {
b[0] = 0
clearbuf(pbuf[:i+1])
}
if b[0] == '\n' || b[0] == '\r' {
return pbuf[:i], nil
}
pbuf[i] = b[0]
b[0] = 0
}
clearbuf(pbuf[:i+1])
return nil, errors.New("ran out of bufferspace")
}
示例6: Write
func (srv *Grande) Write(req *vtsrv.Req) {
var f *os.File
var n int
s := srv.calcScore(req.Tc.Data)
dname := fmt.Sprintf("%s/%02x/%02x", srv.topDir, s[0], s[1])
err := os.MkdirAll(dname, 0777)
if err != nil {
req.RespondError(err.Error())
return
}
f, err = os.OpenFile(srv.Name(s), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
req.RespondError(err.Error())
return
}
defer f.Close()
n, err = f.Write(req.Tc.Data)
if err != nil {
req.RespondError(err.Error())
return
}
if n != len(req.Tc.Data) {
req.RespondError("short write")
return
}
req.RespondWrite(s)
}
示例7: 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
}
示例8: WriteGroups
func WriteGroups(hostFile *os.File) {
for groupName, group := range Groups {
header := fmt.Sprintf("[%s]\n", groupName)
keys := make([]string, 0)
for k, v := range AnsibleInstances {
for _, g := range group {
if *v.ImageID == g {
keys = append(keys, k)
}
}
}
sort.Strings(keys)
hostFile.Write([]byte(header))
for _, k := range keys {
v, _ := AnsibleInstances[k]
err := hostTemplate.Execute(hostFile, v)
if err != nil {
panic(err)
}
}
hostFile.Write([]byte("\n"))
}
}
示例9: Sign
func Sign(privateKeyFileName string, readPass readPasswordCallback, fileToSign string, signatureFile string) (err error) {
var signer *openpgp.Entity
if signer, err = readPrivateKeyFile(privateKeyFileName, readPass); err != nil {
return err
}
var message *os.File
if message, err = os.Open(fileToSign); err != nil {
return err
}
defer message.Close()
var w *os.File
if w, err = os.Create(signatureFile); err != nil {
return err
}
defer w.Close()
if err = openpgp.ArmoredDetachSign(w, signer, message, nil); err != nil {
return err
}
w.Write([]byte("\n"))
return nil
}
示例10: PutData2
func (u *U16x16) PutData2(data []byte, key string) (length int64, hash string, err error) {
s := sha256.New()
s.Write(data)
hash = hex.EncodeToString(s.Sum(nil))
if hash != key {
fmt.Printf("expected data to have key %s, but content key is %s",
key, hash)
err = errors.New("content/key mismatch")
return
}
length = int64(len(data))
topSubDir := hash[0:1]
lowerDir := hash[1:2]
targetDir := filepath.Join(u.path, topSubDir, lowerDir)
found, err := xf.PathExists(targetDir)
if err == nil && !found {
err = os.MkdirAll(targetDir, 0775)
}
fullishPath := filepath.Join(targetDir, key[2:])
found, err = xf.PathExists(fullishPath)
if !found {
var dest *os.File
dest, err = os.Create(fullishPath)
if err == nil {
var count int
defer dest.Close()
count, err = dest.Write(data)
if err == nil {
length = int64(count)
}
}
}
return
}
示例11: receive
func (l *Logger) receive() {
today := time.Now()
var file *os.File
var err error
for data := range l.in {
if l.dir != "" && (file == nil || today.Day() != time.Now().Day()) {
l.mu.Lock()
today = time.Now()
file, err = os.OpenFile(fmt.Sprintf("%s/%s_%s.log", l.dir, l.obj, today.Format("2006-01-02")), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
if err != nil {
panic(err)
}
l.mu.Unlock()
if l.flag&Ldaily != 0 {
go l.rotate(today)
}
}
if file != nil {
file.Write(data)
}
if l.out != nil {
l.out.Write(data)
}
}
}
示例12: withFile
func withFile(name string, content string, action func(f *os.File)) error {
var (
err error
f *os.File
)
withError := func(action func()) {
if err != nil {
return
}
action()
}
func() {
withError(func() { f, err = os.Create(name) })
if err == nil {
defer f.Close()
}
withError(func() { _, err = f.Write([]byte(content)) })
withError(func() { _, err = f.Seek(0, 0) })
action(f)
}()
withError(func() { err = os.Remove(name) })
if err == nil {
return nil
}
return ioError
}
示例13: WriteBytesToFile
func WriteBytesToFile(filePath string, data []byte, append bool) error {
var f *os.File
var err error
if append == true {
if _, err := os.Stat(filePath); os.IsNotExist(err) {
f, err = os.Create(filePath)
if err != nil {
return err
}
f.Close()
}
// open files r and w
f, err = os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
return err
}
} else {
f, err = os.Create(filePath)
if err != nil {
return err
}
}
defer f.Close()
_, err = f.Write(data)
return err
}
示例14: appendRegion
func appendRegion(rid int64, f *os.File, regionSizeB int64) (*region, error) {
size, err := f.Seek(0, os.SEEK_END)
if err != nil {
return nil, err
}
if err := f.Truncate(size + regionSizeB); err != nil {
return nil, err
}
// Initialize header
header := make([]byte, regionHeaderSize)
copy(header[:8], signature)
*(*int64)(unsafe.Pointer(&header[regionFreePointerOffset])) = regionHeaderSize
*(*int64)(unsafe.Pointer(&header[regionSizeOffset])) = regionSizeB
*(*int64)(unsafe.Pointer(&header[regionId])) = rid
if _, err := f.Write(header); err != nil {
return nil, err
}
r, err := openRegion(f, true, size)
if err != nil {
return nil, err
}
r.initBlockList()
return r, nil
}
示例15: bundleReset
func bundleReset(w *os.File, size int64) error {
pending_offset := size - ENDSIZE
if size == 0 {
pending_offset = 0
}
offset, err := w.Seek(pending_offset, 0)
if err != nil {
return err
}
if offset != pending_offset {
return errors.New("Failed to seek!")
}
err = w.Truncate(size)
if err != nil {
return err
}
if size == 0 {
return nil
}
n, err := w.Write(zeroEnd)
if err != nil || n != len(zeroEnd) {
return errors.New("Failed to write end block")
}
return nil
}