Cannot access the file because it is being used by another process - Best practice

Hi,

New to Go, and to programming in general.
I have crated an app that store locally logging info into a text.log file every time something is done by the different functions (i.e. copying files from a folder to some other folders, or deleting files from a folder). This works OK, however I quickly ran into the problem that if the text.log file is being used by another program that locks it (e.g. Excel, for inspection by a colleague) the app crashes.
I really want the logging info to be stored into the text.log file, without waiting for the file to be closed by the other program/colleague (as this could easily take hours/days).

Using the following example, what can I do as best practice to avoid the crash if text.log is open and locked by another program?

package main

import (
	"log"
	"os"
)

func main() {
	f, err := os.OpenFile("text.log",
		os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		log.Println(err)
	}
	defer f.Close()
	if _, err := f.WriteString("text to append\n"); err != nil {
		log.Println(err)
	}
}

Thanks.

I think the problem is that you are opening the file only for writing so if it is locked for another process your program will panic.
Maybe using O_RDWR could solve the problem altough I thinnk you would need to close the file in the locking process…

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.