Go language | Are you still getting the file size like this?

In a project, we may need to get the size of a file. In Golang (Go language), there are many ways to get the size of a file to see if you are still using the slowest way.

Read byte method

The first one is the most intuitive to think of, which is to open the file and read the file again.

func main() {
    file,err:=os.Open("water")
    if err ==nil {
        sum := 0
        buf:=make([]byte,2014)
        for  {
            n,err:=file.Read(buf)
            sum+=n
            if err==io.EOF {
                break
            }
        }
        fmt.Println("file size is ",sum)
    }
}

This method needs to open the file, read the byte content of the file through a for loop, and then calculate the size of the file, which is also the most unusable method because of low efficiency and large amount of code.

ioutil method

The above code is rather long-winded. At this time, we may think of using the ReadFile of the ioutil package instead, to directly obtain the content of the file, and then calculate the size of the file.

func main() {
    content,err:=ioutil.ReadFile("water")
    if err == nil {
        fmt.Println("file size is ",len(content))
    }
}

Through the ioutil.ReadFile function, we can do it with three lines of code, which is indeed a lot more convenient, but the problem of slow efficiency still exists. What if it is a large file?

Stat method

Going further, we do not read the content of the file to calculate, we pass the information of the file

func main() {
    file,err:=os.Open("water")

    if err == nil {
        fi,_:=file.Stat()
        fmt.Println("file size is ",fi.Size())
    }
}

This method will no longer read the content of the file, but directly obtain it through the Stat method, which will be very fast, especially useful for large files. But it is not the ultimate solution we are going to talk about today, because it will still open the file and occupy it.

Ultimate solution

Well, our ultimate solution is finally coming, and his code is very simple.

func main() {
    fi,err:=os.Stat("water")
    if err ==nil {
        fmt.Println("file size is ",fi.Size(),err)
    }
}

Yes, it only takes three lines of code to achieve this. Here we use os.Stat, through which we can get the metadata information of the file. Now let's see what information it can get.

Get file information

Through the os.Stat method, we can get information about the file, such as file size, name, etc.

func main() {
    fi,err:=os.Stat("water")
    if err ==nil {
        fmt.Println("name:",fi.Name())
        fmt.Println("size:",fi.Size())
        fmt.Println("is dir:",fi.IsDir())
        fmt.Println("mode::",fi.Mode())
        fmt.Println("modTime:",fi.ModTime())
    }
}

Run this code to see the result:

name: water
size: 403
is dir: false
mode:: -rw-r--r--
modTime: 2018-05-06 18:52:07 +0800 CST

The above is the file information that can be obtained, including whether it is a directory, permission mode and modification time. Therefore, we need to use the os.Stat function to obtain file information, which can efficiently obtain file information without opening the file.

Check if the file exists

The os.Stat function has two return values, one is the file information and the other is err, through which we can judge whether the file exists.

First, when err==nil, the file definitely exists; secondly, when err!=nil, it does not mean that it does not exist. At this time, we need to make a strict judgment.

func main() {
    _,err:=os.Stat(".")
    if err ==nil {
        fmt.Println("file exist")
    }else if os.IsNotExist(err){
        fmt.Println("file not exist")
    }else{
        fmt.Println(err)
    }
}

Use os.IsNotExist to determine that a file does not exist. In the end, the possibility of else is relatively small. At this time, you can see what the specific error is, and then judge whether the file exists according to the error.

summary

os.Stat is a very good function that allows us to obtain file information very efficiently, so use it as much as possible in the project.

This article is an original article, reprint and indicate the source, welcome to scan the code and pay attention to the public account flysnow_org or the website www.flysnow.org/ , and read the follow-up wonderful articles for the first time. If you like it, please give it a thumbs up.

Tags: Go

Posted by imagenesis on Wed, 25 May 2022 23:51:37 +0300