當前位置: 首頁>>代碼示例>>Golang>>正文


Golang File.WriteString方法代碼示例

本文整理匯總了Golang中os.File.WriteString方法的典型用法代碼示例。如果您正苦於以下問題:Golang File.WriteString方法的具體用法?Golang File.WriteString怎麽用?Golang File.WriteString使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在os.File的用法示例。


在下文中一共展示了File.WriteString方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: WriteToFile

func WriteToFile(FileName, Content string) {

	var outputFile *os.File

	OpenedFileLocker.RLock()
	for key, value := range OpenedFile {
		if key == FileName {
			outputFile = value
			break
		}
	}
	OpenedFileLocker.RUnlock()

	if outputFile == nil {
		tmpFileName := fmt.Sprintf("../UserId/%s.%d", FileName, time.Now().Unix())
		tmpoutputFile, outputError := os.OpenFile(tmpFileName, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0)
		if outputError != nil {
			fmt.Println("An error occurred on opening the outputFile : ", outputError)
			return
		}
		outputFile = tmpoutputFile

		//outputFile.WriteString("\n\n" + time.Now().String() + "\n")

		OpenedFileLocker.Lock()
		OpenedFile[FileName] = outputFile
		OpenedFileLocker.Unlock()
	}
	outputFile.WriteString(Content + "\n")
	//defer outputFile.Close()
}
開發者ID:wujunjian,項目名稱:go,代碼行數:31,代碼來源:file.go

示例2: write

func write(where *os.File, what string) {
	_, err := where.WriteString(what + "\n")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
開發者ID:markalderson,項目名稱:iconize,代碼行數:7,代碼來源:iconize.go

示例3: writeLines

func writeLines(lines []string, path string) (err error) {
	var (
		file *os.File
	)

	if file, err = os.Create(path); err != nil {
		return
	}
	defer file.Close()

	//writer := bufio.NewWriter(file)
	for _, item := range lines {
		//fmt.Println(item)
		_, err := file.WriteString(strings.TrimSpace(item) + "\n")
		//file.Write([]byte(item));
		if err != nil {
			//fmt.Println("debug")
			fmt.Println(err)
			break
		}
	}
	/*content := strings.Join(lines, "\n")
	  _, err = writer.WriteString(content)*/
	return
}
開發者ID:bussiere,項目名稱:VoyageLondre,代碼行數:25,代碼來源:compilemarkdown.go

示例4: generateHtmlHeader

//
// Generate Header of html and write to the @fo
// @prespace mean how many upper to the resource of css and js
//
func generateHtmlHeader(fo *os.File, title string, prespace int) error {
	if fo == nil {
		return errors.New("No File Out Handle")
	}

	fo.WriteString("<!-- This file is generated by jkparsedoc -->\n")
	html_header := "<!DOCTYPE html>\n" +
		"<html lang='zh'>\n" +
		"<head>\n" +
		"\t<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>\n" +
		"\t<title>" + title + "</title>\n" +
		"\t<link rel='shortcut icon' href='/static/imgs/favicon.ico' />\n" +
		"\t<link rel='icon' href='/static/imgs/favicon.png' type='image/png'>\n" +
		"\t<meta name='viewport' content='width=device-width, initial-scale=1.0'>\n" +
		"\t<meta name='description' content=''>\n" +
		"\t<meta name='author' content='jmdvirus'>\n" +
		"\t<!--[if lt IE 9]>\n" +
		"\t\t<script src='http://html5shim.googlecode.com/svn/trunk/html5.js'></script>\n" +
		"\t<![endif]-->\n" +
		"\n" +
		"\t<!-- bootstrap css -->\n" +
		"\t<link href='/static/css/bootstrap.min.css' rel='stylesheet'>\n" +
		"\t<link href='/static/css/bootstrap-theme.min.css' rel='stylesheet'>\n" +
		"</head>\n" +
		"<body>\n" +
		"<div class='container'>\n"
	fo.WriteString(html_header)

	return nil
}
開發者ID:jmdkina,項目名稱:jkgo,代碼行數:34,代碼來源:generateFile.go

示例5: setupTerminal

func setupTerminal(file *os.File) (*sys.Termios, error) {
	fd := int(file.Fd())
	term, err := sys.NewTermiosFromFd(fd)
	if err != nil {
		return nil, fmt.Errorf("can't get terminal attribute: %s", err)
	}

	savedTermios := term.Copy()

	term.SetICanon(false)
	term.SetEcho(false)
	term.SetVMin(1)
	term.SetVTime(0)

	err = term.ApplyToFd(fd)
	if err != nil {
		return nil, fmt.Errorf("can't set up terminal attribute: %s", err)
	}

	// Set autowrap off
	file.WriteString("\033[?7l")

	err = sys.FlushInput(fd)
	if err != nil {
		return nil, fmt.Errorf("can't flush input: %s", err)
	}

	return savedTermios, nil
}
開發者ID:tw4452852,項目名稱:elvish,代碼行數:29,代碼來源:editor.go

示例6: TestRulesFileDoesNotExist

func (t *FileConfigTest) TestRulesFileDoesNotExist(c *C) {
	var fconf, rconf *os.File
	var err error
	var conf Config

	fconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	rconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	defer (func() {
		fconf.Close()
		rconf.Close()
	})()

	// Trailing \n is required by go-config issue #3.
	fconf.WriteString("[Settings]\nloglevel=debug\nrules=\n")
	fconf.Sync()

	conf, err = NewFileConfig(fconf.Name())
	c.Check(conf, Equals, (*FileConfig)(nil))
	c.Check(err, Not(Equals), nil)
}
開發者ID:jeady,項目名稱:lmk,代碼行數:26,代碼來源:file_config_test.go

示例7: AlgorithmRunOnDataSet

func AlgorithmRunOnDataSet(classifier algo.Classifier, train_dataset, test_dataset *core.DataSet, pred_path string, params map[string]string) (float64, []*eval.LabelPrediction) {

	if train_dataset != nil {
		classifier.Train(train_dataset)
	}

	predictions := []*eval.LabelPrediction{}
	var pred_file *os.File
	if pred_path != "" {
		pred_file, _ = os.Create(pred_path)
	}
	for _, sample := range test_dataset.Samples {
		prediction := classifier.Predict(sample)
		if pred_file != nil {
			pred_file.WriteString(strconv.FormatFloat(prediction, 'g', 5, 64) + "\n")
		}
		predictions = append(predictions, &(eval.LabelPrediction{Label: sample.Label, Prediction: prediction}))
	}
	if pred_path != "" {
		defer pred_file.Close()
	}

	auc := eval.AUC(predictions)
	return auc, predictions
}
開發者ID:julycoding,項目名稱:hector,代碼行數:25,代碼來源:algo_runner.go

示例8: writePlainIteratorOnFile

// writePlainIteratorOnFile puts on a file, the list of all the lemmas known.
// Instead of printing one word per line (alphabetically ordered), there is a
// soft-wrap at 80 characters.
func writePlainIteratorOnFile(i *mgo.Iter, f *os.File) (c int) {
	var err error
	var s struct {
		Lemma string
	}
	var ll int
	for i.Next(&s) {

		ss := s.Lemma
		ll += len(ss) + 1 // spaces counts...
		format := "%s "

		if ll > 80 {
			format = "\n%s "
			ll = len(ss)
		}
		if _, err = f.WriteString(fmt.Sprintf(format, ss)); err != nil {
			log.Fatalf("Error dumping: %s\n", err.Error())
		}
		c++
	}

	defer func() {
		if err = i.Close(); err != nil {
			return
		}
	}()
	return
}
開發者ID:zeroed,項目名稱:dictionaries,代碼行數:32,代碼來源:dumper.go

示例9: WriteTextToFile

func WriteTextToFile(filePath string, data string, 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.WriteString(data)
	return err
}
開發者ID:infoassure,項目名稱:nsrls,代碼行數:29,代碼來源:file.go

示例10: SaveCmdSet

func (c *cmdSetData) SaveCmdSet(cmdsetName string, cmdset []string) {
	var f *os.File

	fp := getFilePath()
	_, err := os.Stat(fp)
	if err != nil && !os.IsExist(err) {
		f, err = os.Create(fp)
	} else {
		f, err = os.OpenFile(fp, os.O_RDWR|os.O_APPEND, 0660)
	}
	if err != nil {
		quitWithError("Error writing to file: ", err)
	}
	defer f.Close()

	if _, err = f.WriteString("--" + cmdsetName + "\n"); err != nil {
		quitWithError("Error writing to file: ", err)
	}

	for _, str := range cmdset {
		if _, err = f.WriteString("  " + str + "\n"); err != nil {
			quitWithError("Error writing to file: ", err)
		}
	}

}
開發者ID:zrob,項目名稱:cli-plugin-recorder,代碼行數:26,代碼來源:data.go

示例11: dumpChunk

// dumps a specific chunk, reading chunk info from the cchunk channel
func dumpChunk(cc string) {
	var out *os.File
	dbcon := autorc.New("tcp", "", host+":"+port, user, password, schema)
	defer func() {
		out.Close()
		if err := recover(); err != nil {
			die(err.(error).Error())
		}
		wg.Done()
	}()

	for {
		cr := <-cchunks
		out, _ = os.Create(path + "/" + schema + "." + table + "." + strconv.Itoa(cr.lower) + "." + strconv.Itoa(cr.upper) + ".csv")
		rows, _, _ := dbcon.Query("select * from " + schema + "." + table + " where " + cc + " between " + strconv.Itoa(cr.lower) + " and " + strconv.Itoa(cr.upper))
		for _, row := range rows {
			line := ""

			for idx, _ := range row {
				comma := ","
				if idx == len(row)-1 {
					comma = ""
				}
				line += row.Str(idx) + comma
			}

			out.WriteString(line + "\n")
		}
		if done {
			return
		}
	}
}
開發者ID:fipar,項目名稱:mychunker,代碼行數:34,代碼來源:mychunker.go

示例12: WriteFile

// 寫入文件
// filePath:文件夾路徑
// fileName:文件名稱
// ifAppend:是否追加內容
// args:可變參數
func WriteFile(filePath, fileName string, ifAppend bool, args ...string) {
	// 得到最終的fileName
	fileName = filepath.Join(filePath, fileName)

	// 判斷文件夾是否存在,如果不存在則創建
	mutex.Lock()
	if !IsDirExists(filePath) {
		os.MkdirAll(filePath, os.ModePerm|os.ModeTemporary)
	}
	mutex.Unlock()

	// 打開文件(如果文件存在就以讀寫模式打開,並追加寫入;如果文件不存在就創建,然後以讀寫模式打開。)
	var f *os.File
	var err error
	if ifAppend == false {
		f, err = os.OpenFile(fileName, os.O_CREATE|os.O_RDWR|os.O_TRUNC, os.ModePerm|os.ModeTemporary)
	} else {
		f, err = os.OpenFile(fileName, os.O_CREATE|os.O_RDWR|os.O_APPEND, os.ModePerm|os.ModeTemporary)
	}

	if err != nil {
		fmt.Println("打開文件錯誤:", err)
		return
	}
	defer f.Close()

	// 寫入內容
	for _, arg := range args {
		f.WriteString(arg)
	}
}
開發者ID:Jordanzuo,項目名稱:goutil,代碼行數:36,代碼來源:file.go

示例13: httpRequest

func httpRequest(lines []string, stats *HttpStats, errorFile *os.File, mutex *sync.Mutex) {
	for {
		offset := atomic.AddInt64(&stats.doneRequests, 1)
		if int(offset) > len(lines) {
			break
		}
		line := lines[offset-1]

		// format: [Method URL BodyParameters(for POST)]
		items := strings.Split(line, " ")
		var body io.Reader
		if len(items) > 2 {
			body = strings.NewReader(items[2])
		}

		req, _ := http.NewRequest(items[0], items[1], body)
		client := new(http.Client)

		start := time.Now()
		resp, err := client.Do(req)
		end := time.Now()

		interval := int64(end.Sub(start).Nanoseconds())
		atomic.AddInt64(&stats.accumLatencies, interval)
		if err != nil {
			atomic.AddInt64(&stats.numFailed, 1)
			mutex.Lock()
			errorFile.WriteString(err.Error() + "\n")
			mutex.Unlock()
		} else {
			atomic.AddInt64(&stats.numSucceeded, 1)
		}
		resp.Body.Close()
	}
}
開發者ID:feeblefakie,項目名稱:misc,代碼行數:35,代碼來源:httpbench.go

示例14: LogProcessor

func LogProcessor(in chan gears.RFMessage) {
	os.Mkdir(logDir, 0775)
	go func() {
		var log_fd *os.File
		log_name := ""
		for m := range in {
			// Format the string
			t := time.Now().Format("2006-01-02 15:04:05")
			str := fmt.Sprintf("%s %02x %02d %02x %02d: % x\n",
				t, m.Group, m.Node, m.Kind, len(m.Data)+1, m.Data)
			// Open log file if necessary
			name := fmt.Sprintf("%s/%s.wd", logDir, time.Now().Format("2006-01-02"))
			if name != log_name {
				if log_fd != nil {
					log_fd.Close()
				}
				log_name = name
				var err error
				log_fd, err = os.OpenFile(log_name,
					os.O_WRONLY+os.O_APPEND+os.O_CREATE, 0664)
				if err != nil {
					glog.Errorf("Cannot open %s: %s", log_name, err.Error())
					log_name = ""
				}
			}
			// Write data
			_, err := log_fd.WriteString(str)
			if err != nil {
				glog.Errorf("Error writing %s: %s", log_name, err.Error())
				log_name = ""
			}
		}
	}()
}
開發者ID:kaaLabs15,項目名稱:widuino,代碼行數:34,代碼來源:log_writer.go

示例15: load_config

func load_config(
	config string,
	rules string,
	c *C) (conf *FileConfig, cleanup func()) {
	var fconf, rconf *os.File
	var err error

	fconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	rconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	cleanup = func() {
		fconf.Close()
		rconf.Close()
	}

	// Trailing \n is required by go-config issue #3.
	fconf.WriteString(
		"[Settings]\n" + config + "\n" + "rules=" + rconf.Name() + "\n")
	fconf.Sync()
	rconf.WriteString(rules + "\n")
	rconf.Sync()

	conf, err = NewFileConfig(fconf.Name())
	c.Assert(conf, Not(Equals), nil)
	c.Assert(err, Equals, nil)
	return
}
開發者ID:jeady,項目名稱:lmk,代碼行數:32,代碼來源:file_config_test.go


注:本文中的os.File.WriteString方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。