file Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/file/ Fri, 17 Apr 2020 17:41:21 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://i0.wp.com/golangbyexamples.com/wp-content/uploads/2021/05/cropped-go_border-1.png?fit=32%2C32&ssl=1 file Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/file/ 32 32 159787465 Change file permissions in Go (Golang) https://vikasboss.github.io/change-file-permissions-golang/ https://vikasboss.github.io/change-file-permissions-golang/#respond Fri, 17 Apr 2020 17:41:09 +0000 https://vikasboss.github.io/?p=2031 os.Chmod() function can be used to change the permissions of an existing file. Below is the signature of the function Code Output:

The post Change file permissions in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
os.Chmod() function can be used to change the permissions of an existing file. Below is the signature of the function

func Chmod(name string, mode FileMode) error

Code

package main

import (
    "fmt"
    "log"
    "os"
)

func main() {
    // Create new file
    new, err := os.Create("new.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer new.Close()

    stats, err := os.Stat("new.txt")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Permission File Before: %s\n", stats.Mode())
    err = os.Chmod("new.txt", 0700)
    if err != nil {
        log.Fatal(err)
    }

    stats, err = os.Stat("new.txt")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Permission File After: %s\n", stats.Mode())
}

Output:

Permission File Before: -rw-r--r--
Permission File After: -rwx------

The post Change file permissions in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/change-file-permissions-golang/feed/ 0 2031
Make a copy of a file in Go (Golang) https://vikasboss.github.io/copy-file-go/ https://vikasboss.github.io/copy-file-go/#respond Thu, 16 Apr 2020 20:34:11 +0000 https://vikasboss.github.io/?p=2027 In this article we will see two methods of copying a file. First Method io.Copy() can be used to create a copy of the file from src to dest. A successful copy...

The post Make a copy of a file in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
In this article we will see two methods of copying a file.

First Method

io.Copy() can be used to create a copy of the file from src to dest. A successful copy will return err != nil instead of err == EOF

Below is the signature of the function. It returns the number of bytes written to the dest

func Copy(dst Writer, src Reader) (written int64, err error)

Code

First create a file named “original.txt” and write some content in it.

package main

import (
    "fmt"
    "io"
    "log"
    "os"
)

// Copy a file
func main() {
    // Open original file
    original, err := os.Open("original.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer original.Close()

    // Create new file
    new, err := os.Create("new.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer new.Close()

    //This will copy
    bytesWritten, err := io.Copy(new, original)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Bytes Written: %d\n", bytesWritten)
}

Output:

Bytes Written: 

Second Method

If the contents of the file is less then we can also read the contents of the file first and then write all the contents to the new file. See below code.

Here also first create a file named “original.txt” and write some content in it

package main
import (
    "io/ioutil"
    "log"
)

// Copy a file
func main() {
    //Read all the contents of the  original file
    bytesRead, err := ioutil.ReadFile("original.txt")
    if err != nil {
        log.Fatal(err)
    }

    //Copy all the contents to the desitination file
    err = ioutil.WriteFile("new.txt", bytesRead, 0755)
    if err != nil {
        log.Fatal(err)
    }
}

Output

new.txt file will have same content as original.txt

The post Make a copy of a file in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/copy-file-go/feed/ 0 2027
Rename file or folder in Go (Golang) https://vikasboss.github.io/rename-file-folder-golang/ https://vikasboss.github.io/rename-file-folder-golang/#respond Wed, 15 Apr 2020 21:15:15 +0000 https://vikasboss.github.io/?p=2004 Overview os.Rename() function can be used to rename a file or folder. Below is the signature of the function. old and new can be fully qualified as well. If the old and...

The post Rename file or folder in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

os.Rename() function can be used to rename a file or folder. Below is the signature of the function.

func Rename(old, new string) error


old and new can be fully qualified as well. If the old and new path doesn’t lie in the same directory then os.Rename() function behaves the same as moving a file or folder.

Code

Renaming a file

Below is code for renaming a file

package main

import (
    "log"
    "os"
)

func main() {
    //Create a file
    file, err := os.Create("temp.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    //Change permission so that it can be moved
    err = os.Chmod("temp.txt", 0777)
    if err != nil {
        log.Println(err)
    }


    err = os.Rename("temp.txt", "newTemp.txt")
    if err != nil {
        log.Fatal(err)
    }
}

Output

First, it will create a file named temp.txt in the current working directory. Then it will rename it to newTemp.txt

Renaming a folder

Below is code for renaming a folder

package main

import (
    "log"
    "os"
)

func main() {
    //Create a directory
    err := os.Mkdir("temp", 0755)
    if err != nil {
        log.Fatal(err)
    }
    err = os.Rename("temp", "newTemp")
    if err != nil {
        log.Fatal(err)
    }
}

Output:

First it will create a folder named temp in current working directory. Then it will rename it to newTemp

The post Rename file or folder in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/rename-file-folder-golang/feed/ 0 2004
Create an empty file in Go (Golang) https://vikasboss.github.io/create-empty-file-go/ https://vikasboss.github.io/create-empty-file-go/#respond Fri, 21 Feb 2020 15:06:25 +0000 https://vikasboss.github.io/?p=1415 Overview os.Create() can be used to create an empty file in go. The signature of the function is Basically this function Create a named file with mode 0666 It truncates the file...

The post Create an empty file in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

os.Create() can be used to create an empty file in go. The signature of the function is

func Create(name string) (*File, error) 

Basically this function

  • Create a named file with mode 0666
  • It truncates the file if it already exits
  • In case of path issue, it returns a Path error
  • It returns a file descriptor which can be used for both reading and write

Code:

package main

import (
    "log"
    "os"
)

func main() {
    file, err := os.Create("emptyFile.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()
}

Output:

Check the contents of the file. It will be empty

The post Create an empty file in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/create-empty-file-go/feed/ 0 1415
Append to an existing file in Go (Golang) https://vikasboss.github.io/append-file-golang/ https://vikasboss.github.io/append-file-golang/#respond Fri, 17 Jan 2020 16:41:27 +0000 https://vikasboss.github.io/?p=1181 os.OpenFile() function of the os package can be used to open to a file in an append mode and then write to it Let’s see an example. In the below program: First,...

The post Append to an existing file in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
os.OpenFile() function of the os package can be used to open to a file in an append mode and then write to it

Let’s see an example. In the below program:

  • First, write to a file using ioutil package
  • Open the file again in Append mode and write the second line to it
  • Read the file to verify the content.
package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "os"
)

func main() {
    //Write first line
    err := ioutil.WriteFile("temp.txt", []byte("first line\n"), 0644)
    if err != nil {
        log.Fatal(err)
    }
    
    //Append second line
    file, err := os.OpenFile("temp.txt", os.O_APPEND|os.O_WRONLY, 0644)
    if err != nil {
        log.Println(err)
    }
    defer file.Close()
    if _, err := file.WriteString("second line"); err != nil {
        log.Fatal(err)
    }
    
    //Print the contents of the file
    data, err := ioutil.ReadFile("temp.txt")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(data))
}

Output:

first line
second line

The post Append to an existing file in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/append-file-golang/feed/ 0 1181
Touch a file in Go (Golang) https://vikasboss.github.io/touch-file-golang/ https://vikasboss.github.io/touch-file-golang/#respond Thu, 16 Jan 2020 18:33:03 +0000 https://vikasboss.github.io/?p=1176 Touching a file means Create an empty file if the file doesn’t already exist If the file already exists then update the modified time of the file. Output: When running the first...

The post Touch a file in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Touching a file means

  • Create an empty file if the file doesn’t already exist
  • If the file already exists then update the modified time of the file.
package main

import (
    "fmt"
    "log"
    "os"
    "time"
)

func main() {
    fileName := "temp.txt"
    _, err := os.Stat(fileName)
    if os.IsNotExist(err) {
        file, err := os.Create("temp.txt")
        if err != nil {
            log.Fatal(err)
        }
        defer file.Close()
    } else {
        currentTime := time.Now().Local()
        err = os.Chtimes(fileName, currentTime, currentTime)
        if err != nil {
            fmt.Println(err)
        }
    }
}

Output:

When running the first time it will create the file. After the first time, it will update the modified time of the file.

The post Touch a file in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/touch-file-golang/feed/ 0 1176
Read a large file Line by Line in Go (Golang) https://vikasboss.github.io/read-large-file-line-by-line-go/ https://vikasboss.github.io/read-large-file-line-by-line-go/#comments Sat, 19 Oct 2019 03:56:42 +0000 https://vikasboss.github.io/?p=288 When it comes to reading large files, obviously we don’t want to load the entire file in memory. bufio package in golang comes to the rescue when reading large files. Let’s say...

The post Read a large file Line by Line in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
When it comes to reading large files, obviously we don’t want to load the entire file in memory. bufio package in golang comes to the rescue when reading large files. Let’s say we have a sample.txt file with below contents

This is an example
to show how
to read file 
line by line.

Here is the program:

package main
import (
    "bufio"
    "fmt"
    "log"
    "os"
)
func main(){
    LinebyLineScan()
}
func LinebyLineScan() {
    file, err := os.Open("./sample.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }
    if err := scanner.Err(); err != nil {
        log.Fatal(err)
    }
}

Output:

This is an example
to show how 
to read file 
line by line.

Note however bufio.Scanner has max buffer size 64*1024 bytes which means in case you file has any line greater than the size of 64*1024, then it will give the error

bufio.Scanner: token too long

The post Read a large file Line by Line in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/read-large-file-line-by-line-go/feed/ 1 288