本文整理汇总了Golang中os.Create函数的典型用法代码示例。如果您正苦于以下问题:Golang Create函数的具体用法?Golang Create怎么用?Golang Create使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Create函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: startProfile
func startProfile() {
if cpuprofile != "" {
f, err := os.Create(cpuprofile)
if err != nil {
log.Fatalf("%v", err)
}
if err := pprof.StartCPUProfile(f); err != nil {
log.Fatalf("%v", err)
}
AtExit(pprof.StopCPUProfile)
}
if memprofile != "" {
if memprofilerate != 0 {
runtime.MemProfileRate = int(memprofilerate)
}
f, err := os.Create(memprofile)
if err != nil {
log.Fatalf("%v", err)
}
AtExit(func() {
runtime.GC() // profile all outstanding allocations
if err := pprof.WriteHeapProfile(f); err != nil {
log.Fatalf("%v", err)
}
})
}
}
示例2: TestSnapshotShouldIsolateNewChangesToSource
func (s *ZfsSnapshotTests) TestSnapshotShouldIsolateNewChangesToSource(c *C) {
v, err := s.VolProv.NewVolume()
c.Assert(err, IsNil)
// a new volume should start out empty:
c.Assert(v.Location(), testutils.DirContains, []string{})
f, err := os.Create(filepath.Join(v.Location(), "alpha"))
c.Assert(err, IsNil)
f.Close()
// sanity check, can we so much as even write a file:
c.Assert(v.Location(), testutils.DirContains, []string{"alpha"})
v2, err := s.VolProv.CreateSnapshot(v)
c.Assert(err, IsNil)
// write another file to the source
f, err = os.Create(filepath.Join(v.Location(), "beta"))
c.Assert(err, IsNil)
f.Close()
// the source dir should contain our changes:
c.Assert(v.Location(), testutils.DirContains, []string{"alpha", "beta"})
// the snapshot should be unaffected:
c.Assert(v2.Location(), testutils.DirContains, []string{"alpha"})
}
示例3: TestUntarPathWithDestinationFile
// Do the same test as above but with the destination as file, it should fail
func TestUntarPathWithDestinationFile(t *testing.T) {
tmpFolder, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpFolder)
srcFile := filepath.Join(tmpFolder, "src")
tarFile := filepath.Join(tmpFolder, "src.tar")
os.Create(filepath.Join(tmpFolder, "src"))
// Translate back to Unix semantics as next exec.Command is run under sh
srcFileU := srcFile
tarFileU := tarFile
if runtime.GOOS == "windows" {
tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
}
cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
_, err = cmd.CombinedOutput()
if err != nil {
t.Fatal(err)
}
destFile := filepath.Join(tmpFolder, "dest")
_, err = os.Create(destFile)
if err != nil {
t.Fatalf("Fail to create the destination file")
}
err = UntarPath(tarFile, destFile)
if err == nil {
t.Fatalf("UntarPath should throw an error if the destination if a file")
}
}
示例4: saveSplitPages
func saveSplitPages(input <-chan *PageContainer) {
featuredFile, err := os.Create(featuredFilePath)
if err != nil {
panic(err)
}
featuredCompressed := gzip.NewWriter(featuredFile)
defer featuredFile.Close()
normalFile, err := os.Create(normalFilePath)
if err != nil {
panic(err)
}
normalCompressed := gzip.NewWriter(normalFile)
defer normalFile.Close()
featuredChannel, featuredWriter := ArticleWriter(featuredCompressed)
normalChannel, normalWriter := ArticleWriter(normalCompressed)
//featuredChannel, featuredWriter := ArticleWriter(featuredFile)
//normalChannel, normalWriter := ArticleWriter(normalFile)
DistrbuteArticles(input, featuredChannel, normalChannel)
// Wait for all writers to finish
<-featuredWriter
<-normalWriter
// Close all the gzip streams
// I tried defering the close
// call but kept getting some EOF errors
featuredCompressed.Close()
normalCompressed.Close()
}
示例5: main
func main() {
f, err := os.Create("cpuprofile")
if err != nil {
panic(err.Error())
}
f2, err := os.Create("memprofile")
if err != nil {
panic(err.Error())
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
defer pprof.WriteHeapProfile(f2)
m := radix.NewTree()
var k []byte
for i := 0; i < 100000; i++ {
k = murmur.HashString(fmt.Sprint(i))
m.Put(k, k, 1)
x, _, _ := m.Get(k)
if bytes.Compare(x, k) != 0 {
panic("humbug")
}
}
}
示例6: Profile
// Profile starts CPU and memory profiling and returns a function that will stop that.
//
//
// Writes "cpu" + filename and "mem" + filename.
//
// Usage:
//
// defer Profile("logfast.prof")()
//
func Profile(filename string) func() {
cpu, err := os.Create("cpu" + filename)
if err != nil {
panic(err)
}
mem, err := os.Create("mem" + filename)
if err != nil {
panic(err)
}
then := time.Now()
log.Printf("Profile starting %s\n", filename)
pprof.StartCPUProfile(cpu)
pprof.WriteHeapProfile(mem)
return func() {
elapsed := time.Now().Sub(then)
log.Printf("Profile stopping %s (elapsed %v)\n", filename, elapsed)
pprof.StopCPUProfile()
if err := mem.Close(); err != nil {
log.Printf("error closing mem profile (%v)", err)
}
}
}
示例7: initLogs
func (DS *MainSearch) initLogs(logdir string) {
// open logs
DS.logDir = logdir
os.Mkdir(DS.logDir, os.ModePerm)
tmpF0, err5 := os.Create(DS.logDir + "main:err.log")
if err5 != nil {
log.Fatal("couldn't create errs log", err5)
}
DS.errLogBuf = bufio.NewWriter(tmpF0)
DS.errLogBuf.Flush()
DS.errLog = log.New(DS.errLogBuf, "", log.LstdFlags)
tmpF1, err1 := os.Create(DS.logDir + "main:main.log")
if err1 != nil {
log.Fatal("couldn't create main log", err1)
}
DS.mainLogBuf = bufio.NewWriter(tmpF1)
DS.mainLogBuf.Flush()
DS.mainLog = log.New(DS.mainLogBuf, "", log.LstdFlags)
tmpF2, err2 := os.Create(DS.logDir + "main:eqns.log")
if err2 != nil {
log.Fatal("couldn't create eqns log", err2)
}
DS.eqnsLogBuf = bufio.NewWriter(tmpF2)
DS.eqnsLogBuf.Flush()
DS.eqnsLog = log.New(DS.eqnsLogBuf, "", log.LstdFlags)
}
示例8: encrypt_part_of_file
func encrypt_part_of_file(input_file io.ReaderAt, key_filename, output_filename string, chunk_len, chunk_num, from int64) {
data := make([]byte, chunk_len)
key := make([]byte, chunk_len)
xored_data := make([]byte, chunk_len)
var err error
output_file, err := os.Create(output_filename)
check(err)
defer output_file.Close()
key_file, err := os.Create(key_filename)
check(err)
defer output_file.Close()
for i := int64(0); i < chunk_num; i++ {
n, err := input_file.ReadAt(data, from+i*chunk_len)
if err != nil && err != io.EOF {
panic(err)
}
_, err = rand.Read(key[:n])
check(err)
_, err = key_file.WriteAt(key[:n], from+i*chunk_len)
check(err)
xor(data[:n], key[:n], xored_data[:n])
_, err = output_file.WriteAt(xored_data[:n], from+i*chunk_len)
check(err)
}
}
示例9: TestWriteCLITo
func TestWriteCLITo(t *testing.T) {
modelBuf := bytes.Buffer{}
if err := bgpRouteXMLModel.WriteCLITo(&modelBuf); err != nil {
t.Error(err)
}
fileBuf := bytes.Buffer{}
if file, err := os.Open(BGP_CLI_FILE); err != nil {
t.Error(err)
} else if _, err := fileBuf.ReadFrom(file); err != nil {
t.Error(err)
}
if !bytes.Equal(modelBuf.Bytes(), fileBuf.Bytes()) {
f1, f2 := "model.cli", "current.cli"
if file1, err := os.Create(f1); err != nil {
t.Error(err)
} else if file2, err := os.Create(f2); err != nil {
t.Error(err)
} else {
t.Logf("writing output files for diff: %s, %s", f1, f2)
file1.Write(modelBuf.Bytes())
file2.Write(fileBuf.Bytes())
t.Error("model for CLI parse does not match")
}
}
}
示例10: main
func main() {
runtime.GOMAXPROCS(8)
flag.Parse()
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
fmt.Errorf("%s\n", err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
file, _ := os.Create("./log.txt")
os.Stdout = file
os.Stderr = file
os.Stdin = file
defer file.Close()
Start()
if *memprofile != "" {
f, err := os.Create(*memprofile)
if err != nil {
fmt.Errorf("%s\n", err)
}
pprof.WriteHeapProfile(f)
f.Close()
return
}
}
示例11: startProfiling
// Starts all profiles set on the options.
func (cmd *BenchCommand) startProfiling(options *BenchOptions) {
var err error
// Start CPU profiling.
if options.CPUProfile != "" {
cpuprofile, err = os.Create(options.CPUProfile)
if err != nil {
fmt.Fprintf(cmd.Stderr, "bench: could not create cpu profile %q: %v\n", options.CPUProfile, err)
os.Exit(1)
}
pprof.StartCPUProfile(cpuprofile)
}
// Start memory profiling.
if options.MemProfile != "" {
memprofile, err = os.Create(options.MemProfile)
if err != nil {
fmt.Fprintf(cmd.Stderr, "bench: could not create memory profile %q: %v\n", options.MemProfile, err)
os.Exit(1)
}
runtime.MemProfileRate = 4096
}
// Start fatal profiling.
if options.BlockProfile != "" {
blockprofile, err = os.Create(options.BlockProfile)
if err != nil {
fmt.Fprintf(cmd.Stderr, "bench: could not create block profile %q: %v\n", options.BlockProfile, err)
os.Exit(1)
}
runtime.SetBlockProfileRate(1)
}
}
示例12: writeOutput
func writeOutput(filename string, data []byte) {
var file *os.File
var err error
// prepare output file
if *out == "" {
file, err = os.Create(filename + ".go")
checkOutputFailure(err)
defer file.Close()
} else {
file, err = os.Create(*out)
checkOutputFailure(err)
defer file.Close()
}
output := bufio.NewWriter(file)
// write package clause if any
if *pkg == "" {
path, err := filepath.Abs(*out)
checkOutputFailure(err)
_, err = fmt.Fprintf(output, "package %s\n\n", filepath.Base(filepath.Dir(path)))
checkOutputFailure(err)
} else {
_, err = fmt.Fprintf(output, "package %s\n\n", *pkg)
checkOutputFailure(err)
}
// write data
writeData(filename, data, output)
// flush
err = output.Flush()
checkOutputFailure(err)
}
示例13: BuildEgg
// Build an egg and returns:
// => egg file path, tmpdir with egg creation data, error in case exists
func BuildEgg() (string, string, error) {
closest_cfg := closest_scrapy_cfg(".", "")
err := os.Chdir(filepath.Dir(closest_cfg))
if err != nil {
return "", "", err
}
// if not exists 'setup.py'
if _, err := os.Stat("setup.py"); err != nil {
settings, ok := scrapy_get_config()["settings"]
if !ok {
return "", "", errors.New("BuildEgg: No 'settings' section found on scrapy.cfg")
}
createDefaultSetupPy(settings["default"])
}
tmpdir, err := ioutil.TempDir(os.TempDir(), "shubc-deploy")
if err != nil {
return "", "", errors.New("BuildEgg: Can't create temporary directory")
}
cmd := exec.Command("python", "setup.py", "clean", "-a", "bdist_egg", "-d", tmpdir)
tout, _ := os.Create(filepath.Join(tmpdir, "stdout"))
terr, _ := os.Create(filepath.Join(tmpdir, "stderr"))
cmd.Stdout = tout
cmd.Stderr = terr
if err := cmd.Run(); err != nil {
return "", tmpdir, errors.New(fmt.Sprintf("BuildEgg: Can't create egg file - details: %s", err))
}
matches, err := filepath.Glob(filepath.Join(tmpdir, "*.egg"))
if err != nil {
return "", tmpdir, errors.New(fmt.Sprintf("BuildEgg: No '.egg' file foun on %d", tmpdir))
}
tout.Close()
terr.Close()
return matches[0], tmpdir, nil
}
示例14: main
func main() {
flag.Parse()
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
fmt.Println("Error: ", err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
if *memprofile != "" {
f, err := os.Create(*memprofile)
if err != nil {
fmt.Println("Error: ", err)
}
pprof.WriteHeapProfile(f)
}
var wg sync.WaitGroup
cidrs, err := parseCidrs("./hosts.json")
if err != nil {
log.Fatal(err)
}
servers := make([]Server, 0, 10)
for k := range cidrs.Cidrs {
servers = append(servers, Server{Cidr: cidrs.Cidrs[k]})
}
fmt.Println(len(servers))
for k := range servers {
wg.Add(1)
go servers[k].checkIP(&wg)
}
wg.Wait()
}
示例15: createTestFiles
func (r *RestoreSuite) createTestFiles(c *gc.C) {
tarDirE := path.Join(r.cwd, "TarDirectoryEmpty")
err := os.Mkdir(tarDirE, os.FileMode(0755))
c.Check(err, jc.ErrorIsNil)
tarDirP := path.Join(r.cwd, "TarDirectoryPopulated")
err = os.Mkdir(tarDirP, os.FileMode(0755))
c.Check(err, jc.ErrorIsNil)
tarSubFile1 := path.Join(tarDirP, "TarSubFile1")
tarSubFile1Handle, err := os.Create(tarSubFile1)
c.Check(err, jc.ErrorIsNil)
tarSubFile1Handle.WriteString("TarSubFile1")
tarSubFile1Handle.Close()
tarSubDir := path.Join(tarDirP, "TarDirectoryPopulatedSubDirectory")
err = os.Mkdir(tarSubDir, os.FileMode(0755))
c.Check(err, jc.ErrorIsNil)
tarFile1 := path.Join(r.cwd, "TarFile1")
tarFile1Handle, err := os.Create(tarFile1)
c.Check(err, jc.ErrorIsNil)
tarFile1Handle.WriteString("TarFile1")
tarFile1Handle.Close()
tarFile2 := path.Join(r.cwd, "TarFile2")
tarFile2Handle, err := os.Create(tarFile2)
c.Check(err, jc.ErrorIsNil)
tarFile2Handle.WriteString("TarFile2")
tarFile2Handle.Close()
r.testFiles = []string{tarDirE, tarDirP, tarFile1, tarFile2}
}