dongsui4658 2018-12-09 11:39
浏览 26
已采纳

从文件读取并检查文件结尾

I am trying to do the following tasks in Go;

  1. Read from a file
  2. Backup the file
  3. Overwrite and perform actions based on the files output on a character by character basis (which may include newLine characters or "b" for example)

Unfortunately, I am stuck on step 3 and would like some assistance with "new line" characters (i.e. "/n"). I have tried using filesText, err := ioutil.ReadFile(fileNameAndDirectory) but unfortunately if I try and check for file endings after converting filesText to a string I am unable to detect new line characters (i.e. If files text is "/nhello/n" then the following code snippet will not print the string "match"

filesText, err := ioutil.ReadFile(fileNameAndDirectory) 
if (string(filesText)[:2]) == "/n") {
    fmt.Println("match")
}

).

Is there something that I can do to detect new lines without reading the file line by line manually?

Example: If the file contents is "r/n3$/n;" then I should able to perform 6 predefined actions (one for for each character) as I move from left to right over the files contents.

  • 写回答

1条回答 默认 最新

  • duanliang8464 2018-12-09 12:20
    关注

    We can only guess. You haven't defined your problem clearly. Please clarify your specific problem or add additional details to highlight exactly what you need. Provide sample input and output.


    The Go Programming Language Specification

    After a backslash, certain single-character escapes represent special values:

    
       U+000A line feed or newline
    

    Here's a guess:

    lines.go:

    package main
    
    import (
        "fmt"
        "io/ioutil"
        "os"
        "strings"
    )
    
    func lines(data []byte) {
        text := string(data)
        for i, j := 0, 0; j >= 0; i += j + 1 {
            var line string
            j = strings.IndexByte(text[i:], '
    ')
            if j < 0 {
                line = text[i:]
                if len(line) == 0 {
                    continue
                }
            } else {
                line = text[i : i+j+1]
            }
            // process line
            fmt.Printf("%d %q
    ", len(line), line)
        }
    }
    
    func main() {
        filename := `test.file`
        data, err := ioutil.ReadFile(filename)
        if err != nil {
            fmt.Fprintln(os.Stderr, err)
            return
        }
        fmt.Printf("%d %q
    ", len(data), data)
        lines(data)
    }
    

    Output:

    $ cat test.file
    line1
    line2
    line3
    $ go run lines.go
    18 "line1
    line2
    line3
    "
    6 "line1
    "
    6 "line2
    "
    6 "line3
    "
    

    Comment:

    I'll try and clarify it through an example. Let say that I have a file with contents "ara/n;>$g9s", my application will perform an action defined by that input character as it moves through the contents of the file. I.e. If "a" does action 1, "r" does action 2, "/n" does action 3 and so on then the input above will perform the following actions 1,2,1,3... in that order. However, if you turn the byte array to a string then I'm unable to identify "/n" characters since they appear to be removed despite the string having the same formatting as before if you print it out or concat it into a file. – Elliot Smith

    Why do you write /n for a newline character! The newline character U+000A, as I've already pointed out, is written as .

    For example,

    package main
    
    import "fmt"
    
    func es(s string) {
        for _, r := range s {
            switch r {
            case 'a':
                fmt.Printf("action 1 for %q
    ", r)
            case 'r':
                fmt.Printf("action 2 for %q
    ", r)
            case '
    ':
                fmt.Printf("action 3 for %q
    ", r)
            default:
                fmt.Printf("action ? for %q
    ", r)
            }
        }
    }
    
    func main() {
        b := []byte("ara
    ;>$g9s")
        s := string(b)
        es(s)
    }
    

    Playground: https://play.golang.org/p/3J0pxXh3Wkc

    Output:

    action 1 for 'a'
    action 2 for 'r'
    action 1 for 'a'
    action 3 for '
    '
    action ? for ';'
    action ? for '>'
    action ? for '$'
    action ? for 'g'
    action ? for '9'
    action ? for 's'
    

    Revised Question:

    Example: If the file contents is "r/n3$/n;" then I should able to perform 6 predefined actions (one for for each character) as I move from left to right over the files contents. Elliot Smith


    Why do you write /n for a newline character! The newline character U+000A, as I've already pointed out, is written as .

    For example,

    package main
    
    import "fmt"
    
    func es(s string) {
        for _, r := range s {
            switch r {
            case 'a':
                fmt.Printf("action for %q
    ", r)
            case 'r':
                fmt.Printf("action for %q
    ", r)
            case '
    ':
                fmt.Printf("action for %q
    ", r)
            default:
                fmt.Printf("action for %q
    ", r)
            }
        }
    }
    
    func main() {
        file := []byte("r
    3$
    ;")
        s := string(file)
        es(s)
    }
    

    Playground: https://play.golang.org/p/X1gtrPRmlqq

    Output:

    action for 'r'
    action for '
    '
    action for '3'
    action for '$'
    action for '
    '
    action for ';'
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效