本文整理汇总了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()
}
示例2: write
func write(where *os.File, what string) {
_, err := where.WriteString(what + "\n")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
示例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
}
示例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
}
示例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
}
示例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)
}
示例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
}
示例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
}
示例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
}
示例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)
}
}
}
示例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
}
}
}
示例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)
}
}
示例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()
}
}
示例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 = ""
}
}
}()
}
示例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
}