问题描述
这个Go程序说没有文件存在也不存在有什么原因吗?大概是一个或另一个?
包主
导入(
fmt
log
os
path / filepath
)
func main(){
for _,fn:=范围os.Args [1:] {
src,_:= filepath.Abs(fn)
fmt.Println(fn)
fmt.Println(src)
if _,e:= os.Stat(src); os.IsExist(e){
log.Fatalf(Does exists:%s,src)
}
if _,e:= os.Stat(src); os.IsNotExist(e){
log.Fatalf(不存在:%s,src)
}
}
}
os.IsExist和os.IsNotExist函数不会测试相反的条件,即使名称似乎暗示他们这样做。
函数由于文件已经存在而导致操作失败时返回true。当操作因文件不存在而失败时,函数将返回true。
os.Stat函数总是返回一个os.IsExist(err)== false的错误。 os.Stat函数永远不会失败,因为该文件存在。
使用O_CREAT的函数os.OpenFile总是返回一个错误os.IsNotExist(err)== false。因为使用O_CREAT的os.OpenFile的目的是为了创建一个文件,所以这个文件从未丢失。
Is there some reason why this Go program says neither that a file exists nor doesn't exist? Presumably it's one or the other?
package main
import (
"fmt"
"log"
"os"
"path/filepath"
)
func main() {
for _, fn := range os.Args[1:] {
src, _ := filepath.Abs(fn)
fmt.Println(fn)
fmt.Println(src)
if _, e := os.Stat(src); os.IsExist(e) {
log.Fatalf("Does exist: %s", src)
}
if _, e := os.Stat(src); os.IsNotExist(e) {
log.Fatalf("Does not exist: %s", src)
}
}
}
The os.IsExist and os.IsNotExist functions do not test opposite conditions, even though the names seem to imply that they do.
The function os.IsExist returns true when an operation fails because a file already exists. The function os.IsNotExist returns true when the operation fails because the file does not exist.
The function os.Stat always returns an error with os.IsExist(err) == false. The os.Stat function never fails because the file exists.
The function os.OpenFile with O_CREAT always returns an error os.IsNotExist(err) == false. Because the purpose of os.OpenFile with O_CREAT is to create a file, it is never an error for the file to be missing.
这篇关于文件都存在并且不存在于Go?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!