Skip to content

Instantly share code, notes, and snippets.

@manojd929
Created July 25, 2018 18:44
Show Gist options
  • Save manojd929/6f387c8dd65627d342aa83999f6b9fb4 to your computer and use it in GitHub Desktop.
Save manojd929/6f387c8dd65627d342aa83999f6b9fb4 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
type content struct {
Count int
}
func checkFileExists(name string) bool {
_, err := os.Stat(name)
if err != nil {
return os.IsExist(err)
}
return true
}
func updateFileContent(name string) error {
fBlob, err := ioutil.ReadFile(name)
if err != nil {
fmt.Println(name, "ReadFile Error", err)
}
fmt.Println(string(fBlob))
var fContent content
err = json.Unmarshal(fBlob, &fContent)
if err != nil {
fmt.Println("Error Unmarshaling data", err)
return err
}
fContent.Count++
fBlob, err = json.Marshal(fContent)
if err != nil {
fmt.Println("Error Marshaling data", err)
return err
}
err = ioutil.WriteFile(name, fBlob, 0666)
if err != nil {
fmt.Println(name, "Write File Error", err)
}
return nil
}
func createFileContent(name string) error {
fh, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE, 0666)
defer fh.Close()
if err != nil {
fmt.Println(name, "ReadFile Error", err)
}
fContent := content{Count: 1}
fBlob, err := json.Marshal(fContent)
if err != nil {
fmt.Println("Error Marshaling data", err)
return err
}
_, err = fh.Write(fBlob)
if err != nil {
fmt.Println(name, "Write File Error", err)
}
return nil
}
func main() {
var err error
names := []string{"file-1", "file-2", "file-1", "file-2", "file-3", "file-3"}
for _, name := range names {
isFileExists := checkFileExists(name)
fmt.Println(name, "Exists:", isFileExists)
if isFileExists {
err = updateFileContent(name)
if err != nil {
fmt.Println("Error updating file", err)
}
} else {
err = createFileContent(name)
if err != nil {
fmt.Println("Error creating file", err)
}
}
}
// Delete all the files that were created
for _, name := range names {
isFileExists := checkFileExists(name)
if isFileExists {
err = os.Remove(name)
if err != nil {
fmt.Println("Error Removing the file", name, err)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment