golang文件WriteString封面

时间:2017-08-22 03:43:42

标签: go cover

我想用文件获取增量id,代码如下:

// get increment id
func GetID() uint64 {

    appIdLock.Lock()
    defer appIdLock.Unlock()

    f, err := os.OpenFile(idPath, os.O_RDWR, 0666)
    if err != nil {
        return 0
    }
    defer f.Close()

    // Read
    bufferTemp := make([]byte, 16)
    bufferResult := make([]byte, 0)
    for {
        n, _ := f.Read(bufferTemp)
        if n > 0 {
            bufferResult = append(bufferResult, bufferTemp[:n]...)
        } else {
            break
        }
    }

    if len(bufferResult) == 0 {
        return 0
    }

    s := common.StringToUint64(string(bufferResult))
    s += 1

    // Write (how to cover?)
    f.WriteString(strconv.FormatUint(s, 10))

    return s
}

f.WriteString函数被追加,例如,我的文件内容:123,运行GetID()我希望我的文件内容是:124,但结果是:123124

1 个答案:

答案 0 :(得分:1)

在不改变您的大部分代码的情况下,这里的解决方案将起作用并执行您想要执行的操作。没有loops或多于单个字节切片。

func GetID() uint64 {

    appIdLock.Lock()
    defer appIdLock.Unlock()

    // Added  + os.O_CREATE to create the file if it doesn't exist.
    f, err := os.OpenFile(idPath, os.O_RDWR + os.O_CREATE, 0666)
    if err != nil {
        fmt.Println(err)
        return 0
    }
    defer f.Close()

    // Know file content beforehand so I allocate a suitable bytes slice.
    fileStat, err := f.Stat()
    if err != nil {
        fmt.Println(err)
        return 0
    }


    buffer := make([]byte, fileStat.Size())

    _, err = f.Read(buffer)
    if err != nil {
        fmt.Println(err)
        return 0
    }

    s, _ := strconv.ParseUint(string(buffer), 10, 64)
    s += 1

    // The Magic is here ~ Writes bytes at 0 index of the file.
    _, err = f.WriteAt([]byte(strconv.FormatUint(s, 10)), 0)
    if err != nil {
        fmt.Println(err)
        return 0
    }

    return s
}


希望它有所帮助!