登录
首页 >  Golang >  Go问答

以新行为界限划分的写入文件的输入流

来源:stackoverflow

时间:2024-02-29 08:45:21 306浏览 收藏

一分耕耘,一分收获!既然都打开这篇《以新行为界限划分的写入文件的输入流》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!

问题内容

我是 golang 新手,我可能正在尝试做一些不可能的事情。任何帮助,将不胜感激。

我的问题是如何创建一个服务器来获取一条由换行符分隔的消息,并且一旦收到换行符,我想将缓冲区的内容写入一个唯一的文件? p>

我的服务器逻辑看起来相当标准。下面是我的handleconnection 函数,我试图在其中执行上面描述的任务:

func handleConnection(conn net.Conn) {
  // closes the connection on exit
  defer func() {
    if err := conn.Close(); err != nil {
      log.Println("error closing connection: ", err)
    }
  }()

  // create a buffer for the incoming data
  buf := make([]byte, 4096)

  // read the incoming connection into the buffer
  size, err := conn.Read(buf)
  if err != nil {
    fmt.Println("error reading: ", err.Error)
  }

  s := string(buf[:size])
  fmt.Println(s)
  // set the files permissions
  perm := os.FileMode(0777)
  // writes to the file and generates an err value
  err := ioutil.WriteFile("adt_output.txt", buf[:size], perm)
  // if err is not nol show the error
  if err != nil {
    log.Fatal(err)
  }

}

解决方案


例如,您可以使用以下模式来读取直到终止字节:

r := bufio.NewReader(conn)
    for {
        yourLine, err := r.ReadBytes(10)
        ... write your file ...
    }

类似的还有 r.readstring('\n') 也可以。

理论要掌握,实操不能落!以上关于《以新行为界限划分的写入文件的输入流》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>