本文整理汇总了Golang中os.File.Truncate方法的典型用法代码示例。如果您正苦于以下问题:Golang File.Truncate方法的具体用法?Golang File.Truncate怎么用?Golang File.Truncate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os.File
的用法示例。
在下文中一共展示了File.Truncate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: lockPidFile
// Locks PID file with a file lock.
// Keeps PID file open until applications exits.
func lockPidFile() (pidFile *os.File, err error) {
var file *os.File
file, err = os.OpenFile(
PidFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, PidFileMask,
)
if err != nil {
return
}
defer func() {
// file must be open whole runtime to keep lock on itself
if err != nil {
file.Close()
}
}()
if err = syscall.Flock(int(file.Fd()), syscall.LOCK_EX); err != nil {
return
}
var fileLen int
fileLen, err = fmt.Fprint(file, os.Getpid())
if err != nil {
return
}
if err = file.Truncate(int64(fileLen)); err != nil {
return
}
return file, err
}
示例2: fallocate
func fallocate(f *os.File, sz int64) error {
err := syscall.Fallocate(int(f.Fd()), 0, 0, sz)
if err == syscall.ENOTSUP {
return f.Truncate(sz)
}
return err
}
示例3: createDataFile
func createDataFile(name string, length int64) (err error) {
if (length & 3) != 0 {
return fmt.Errorf("createDataFile only supports length that is a multiple of 4. Not %d", length)
}
var file *os.File
file, err = os.Create(name)
if err != nil {
return
}
defer file.Close()
err = file.Truncate(length)
if err != nil {
return
}
w := bufio.NewWriter(file)
b := make([]byte, 4)
for i := int64(0); i < length; i += 4 {
b[0] = byte(i >> 24)
b[1] = byte(i >> 16)
b[2] = byte(i >> 8)
b[3] = byte(i)
_, err = w.Write(b)
if err != nil {
return
}
}
return
}
示例4: 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
}
示例5: FindAndReplaceFd
func FindAndReplaceFd(fd *os.File, oldPattern, newPattern string) error {
fbuf, err := ioutil.ReadAll(fd)
if err != nil {
return err
}
fd.Seek(0, -1)
fd.Truncate(0)
expr, err := regexp.Compile(oldPattern)
if err != nil {
return err
}
buffer := bytes.NewBuffer(fbuf)
for {
line, err := buffer.ReadString('\n')
if err != nil {
if err == io.EOF {
break
}
return err
}
if expr.MatchString(line) {
line = expr.ReplaceAllString(line, newPattern)
}
if _, err := fd.WriteString(line); err != nil {
return err
}
}
return nil
}
示例6: 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
}
示例7: empty
func empty(f *os.File) error {
if err := f.Truncate(0); err != nil {
return err
}
_, err := f.Seek(0, 0)
return err
}
示例8: New
func New(path string) (pf *PidFile, err error) {
pf = &PidFile{path, os.Getpid()}
var f *os.File
f, err = os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
if err != nil {
f, err = os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
return
}
var pidstr [10]byte
var n int
n, err = f.Read(pidstr[:])
if err != nil {
return
}
var pid int
pid, err = strconv.Atoi(string(pidstr[:n]))
if err != nil {
return
}
_, err = os.FindProcess(pid)
if err == nil {
// process exists
err = ProcessExists
return
}
f.Truncate(int64(n))
}
defer f.Close()
_, err = f.WriteString(strconv.Itoa(pf.Pid))
return
}
示例9: testAccCreateZipFromFiles
func testAccCreateZipFromFiles(files map[string]string, zipFile *os.File) error {
zipFile.Truncate(0)
zipFile.Seek(0, 0)
w := zip.NewWriter(zipFile)
for source, destination := range files {
f, err := w.Create(destination)
if err != nil {
return err
}
fileContent, err := ioutil.ReadFile(source)
if err != nil {
return err
}
_, err = f.Write(fileContent)
if err != nil {
return err
}
}
err := w.Close()
if err != nil {
return err
}
return w.Flush()
}
示例10: addTagsToFile
func addTagsToFile(file *os.File, tags []string) (success bool) {
file.Seek(0, 0) // rewind to start with
r, err := ioutil.ReadAll(io.Reader(file))
if err != nil {
log.Printf("ERROR: %s\n", err)
return
}
loc := bytes.Index(r, gitScissorMarker)
if loc < 0 {
if _, err := file.Seek(0, 2); err != nil { // seek to end of file
log.Printf("ERROR: %s\n", err)
return
}
} else {
if _, err := file.Seek(int64(loc), 0); err != nil { // seek to scissor line then truncate the file here
log.Printf("ERROR: %s\n", err)
return
}
if err := file.Truncate(int64(loc + 1)); err != nil {
log.Printf("ERROR: %s\n", err)
return
}
}
fmt.Fprintln(file, "") // blank line first to ensure it's not stuck to the summary
for _, tag := range tags {
fmt.Fprintln(file, tag)
}
return true
}
示例11: 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
}
示例12: TorrentData
func TorrentData(md *metainfo.Info, location string) (ret *torrentData, err error) {
var mms mmap_span.MMapSpan
defer func() {
if err != nil {
mms.Close()
}
}()
for _, miFile := range md.UpvertedFiles() {
fileName := filepath.Join(append([]string{location, md.Name}, miFile.Path...)...)
err = os.MkdirAll(filepath.Dir(fileName), 0777)
if err != nil {
err = fmt.Errorf("error creating data directory %q: %s", filepath.Dir(fileName), err)
return
}
var file *os.File
file, err = os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
return
}
func() {
defer file.Close()
var fi os.FileInfo
fi, err = file.Stat()
if err != nil {
return
}
if fi.Size() < miFile.Length {
err = file.Truncate(miFile.Length)
if err != nil {
return
}
}
if miFile.Length == 0 {
// Can't mmap() regions with length 0.
return
}
var mMap mmap.MMap
mMap, err = mmap.MapRegion(file,
int(miFile.Length), // Probably not great on <64 bit systems.
mmap.RDWR, 0, 0)
if err != nil {
err = fmt.Errorf("error mapping file %q, length %d: %s", file.Name(), miFile.Length, err)
return
}
if int64(len(mMap)) != miFile.Length {
panic("mmap has wrong length")
}
mms.Append(mMap)
}()
if err != nil {
return
}
}
ret = &torrentData{
MMapSpan: mms,
completed: make([]bool, md.NumPieces()),
}
return
}
示例13: touchCheckOkFile
func touchCheckOkFile(f *os.File) (err os.Error) {
name := f.Name() + ".ok"
f, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0660)
if err == nil {
f.Truncate(0)
f.Close()
}
return
}
示例14: TorrentData
func TorrentData(md *metainfo.Info, location string) (mms *mmap_span.MMapSpan, err error) {
mms = &mmap_span.MMapSpan{}
defer func() {
if err != nil {
mms.Close()
mms = nil
}
}()
for _, miFile := range md.UpvertedFiles() {
fileName := filepath.Join(append([]string{location, md.Name}, miFile.Path...)...)
err = os.MkdirAll(filepath.Dir(fileName), 0777)
if err != nil {
err = fmt.Errorf("error creating data directory %q: %s", filepath.Dir(fileName), err)
return
}
var file *os.File
file, err = os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
return
}
func() {
defer file.Close()
var fi os.FileInfo
fi, err = file.Stat()
if err != nil {
return
}
if fi.Size() < miFile.Length {
err = file.Truncate(miFile.Length)
if err != nil {
return
}
}
if miFile.Length == 0 {
// Can't mmap() regions with length 0.
return
}
var mMap gommap.MMap
mMap, err = gommap.MapRegion(file.Fd(), 0, miFile.Length, gommap.PROT_READ|gommap.PROT_WRITE, gommap.MAP_SHARED)
if err != nil {
err = fmt.Errorf("error mapping file %q, length %d: %s", file.Name(), miFile.Length, err)
return
}
if int64(len(mMap)) != miFile.Length {
panic("mmap has wrong length")
}
mms.Append(mMap)
}()
if err != nil {
return
}
}
return
}
示例15: WriteAt
func (r *HdCache) WriteAt(p []byte, off int64) []chunk {
boxI := int(off / int64(r.pieceSize))
boxOff := int(off % int64(r.pieceSize))
for i := 0; i < len(p); {
var box *os.File
var err error
if !r.boxExists.IsSet(boxI) { //box doesn't exist, so we'll make one.
box, err = os.Create(r.boxPrefix + strconv.Itoa(boxI))
if err != nil {
log.Panicln("Couldn't create cache file:", err)
return nil
}
r.boxExists.Set(boxI)
box.Truncate(int64(r.pieceSize))
r.actualUsage++
} else { //box exists, so we'll open it
box, err = os.OpenFile(r.boxPrefix+strconv.Itoa(boxI), os.O_WRONLY, 0777)
if err != nil {
log.Println("Error opening cache item we thought we had:", r.boxPrefix+strconv.Itoa(boxI), "error:", err)
r.removeBox(boxI)
continue //loop around without incrementing 'i', forget this ever happened
}
}
end := r.pieceSize - boxOff
if len(p) < end {
end = len(p)
}
copied, err := box.WriteAt(p[i:end], int64(boxOff))
if err != nil {
log.Panicln("Error at write cache box:", box.Name(), "error:", err)
}
i += copied
box.Close()
r.atimes[boxI] = time.Now()
if copied == r.pieceSize {
r.isBoxFull.Set(boxI)
} else {
if r.isByteSet[boxI].n == 0 {
r.isByteSet[boxI] = *NewBitset(r.pieceSize)
}
for j := boxOff; j < boxOff+copied; j++ {
r.isByteSet[boxI].Set(j)
}
}
boxI++
boxOff = 0
}
if r.actualUsage > r.getCapacity() {
return r.trim()
}
return nil
}