英文:
run go executable file with file i/o
问题
可执行文件tapi
位于bin
文件夹下,在我的Mac上无法创建日志文件。顺便说一下,我已经创建了logs
文件夹。
panic: 打开logs/1435584525.txt时出错:没有这个文件或目录
使用命令行tapi
可以正常运行。
我使用的代码是:
t := time.Now()
filename := "logs/" + strconv.FormatInt(t.Unix(), 10) + ".txt"
logFile, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
panic(err)
}
defer logFile.Close()
log.SetOutput(logFile)
文件结构如下:
bin/tapi
pkg
src/userName/tapi/tapi.go
英文:
The executable file tapi
under folder bin
can't create the log file (in my Mac), btw. I already create the folder logs
panic: open logs/1435584525.txt: no such file or directory
it runs correct with command line tapi
the code I use is:
t := time.Now()
filename := "logs/" + strconv.FormatInt(t.Unix(),10) + ".txt"
logFile, err := os.OpenFile(filename, os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
if err != nil {
panic(err)
}
defer logFile.Close()
log.SetOutput(logFile)
the structure of files is :
bin/tapi
pkg
src/userName/tapi/tapi.go
答案1
得分: 1
问题出在"logs/"这个相对路径上。如果你使用绝对路径(例如创建并使用"/logs/"),那么问题就会解决。
我刚刚安装并成功运行了这段代码(在创建/logs/并设置权限之后):
package main
import (
"log"
"os"
"time"
"strconv"
)
func main() {
t := time.Now()
filename := "/logs/" + strconv.FormatInt(t.Unix(), 10) + ".txt"
logFile, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
panic(err)
}
defer logFile.Close()
log.SetOutput(logFile)
}
如果你保持路径为相对路径,则在目录结构中添加"/src/tapi/logs",它就可以正常工作。
在这种情况下,以下代码对我来说运行良好:
package main
import (
"log"
"os"
"time"
"strconv"
)
func main() {
t := time.Now()
filename := "logs/" + strconv.FormatInt(t.Unix(), 10) + ".txt"
logFile, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
panic(err)
}
defer logFile.Close()
log.SetOutput(logFile)
}
英文:
The problem is the "logs/", which is a relative path. If you used an absolute path (create and use "/logs/" for instance) then that would solve the problem.
I just installed and ran this successfully (after creating /logs/ and setting permissions):
package main
import (
"log"
"os"
"time"
"strconv"
)
func main() {
t := time.Now()
filename := "/logs/" + strconv.FormatInt(t.Unix(), 10) + ".txt"
logFile, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
panic(err)
}
defer logFile.Close()
log.SetOutput(logFile)
}
If you leave the path relative then add: "/src/tapi/logs" in the directory structure and it will work.
Under those circumstances this ran fine for me:
package main
import (
"log"
"os"
"time"
"strconv"
)
func main() {
t := time.Now()
filename := "logs/" + strconv.FormatInt(t.Unix(), 10) + ".txt"
logFile, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
panic(err)
}
defer logFile.Close()
log.SetOutput(logFile)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论