Go語言程式檢查檔案是目錄還是檔案
在 Go 中,目錄是一種特殊的資料夾,用於儲存其他檔案和目錄。目錄用於組織檔案系統中的檔案,併為檔案系統提供結構。Go 在 os 包中提供了多個函式來處理目錄,包括:os.mkdir、os.remove、os.open 等。
語法
func Stat(name string) (fi FileInfo, err error)
Stat() 函式位於 os 包中,用於檢查特定目錄的狀態。該函式接收一個字串引數 name,表示目錄的路徑。它返回一個 FileInfo 結構體 fi 和一個錯誤 err。
演算法
步驟 1 − 首先,我們需要匯入 fmt 和 os 包。
步驟 2 − 然後開始 main() 函式。在 main 函式內部初始化一個名為 file 的變數,並在其中儲存檔案或目錄所在的路徑。
步驟 3 − 現在,使用 IsDir() 方法檢查提供的路徑是檔案還是目錄。如果路徑是目錄,則列印它是目錄。
步驟 4 − 否則,列印路徑是檔案。
示例 1
在這個示例中,我們將使用 os 包中的 isDir() 函式。程式將根據使用者提供的路徑是否指向檔案,顯示結果為目錄或檔案。
package main
import (
"fmt"
"os"
)
func main() {
// providing the path of the file
file := "C:/Users/LENOVO/Desktop/go"
info, err := os.Stat(file)
if err != nil {
fmt.Println(err)
return
}
if info.IsDir() {
fmt.Println("It is a directory")
} else {
fmt.Println("It is a file")
}
}
輸出
It is a directory
示例 2
在這個示例中,我們將使用 os 包中的 Lstat() 方法來查詢使用者提供的檔案是檔案還是目錄。
package main
import (
"fmt"
"os"
)
func main() {
// giving the extension of the file
file := "C:/Users/LENOVO/Desktop/go/newFile.txt"
fileInfo, err := os.Lstat(file)
if err != nil {
fmt.Println(err)
return
}
mode := fileInfo.Mode()
if mode.IsDir() {
fmt.Println("It is a directory")
} else if mode.IsRegular() {
fmt.Println("It is a regular file")
} else {
fmt.Println("It is something else")
}
}
輸出
It is a regular file
示例 3
在這個示例中,我們將使用 OS 包中的 STAT() 方法來查詢使用者提供的檔案是檔案還是目錄。
package main
import (
"fmt"
"os"
)
func main() {
// ENTER THE EXTENSION OF THE FILE OR DIRECTORY
file := "C:/Users/LENOVO/Desktop/go/new.go"
fileInfo, err := os.Stat(file)
if err != nil {
fmt.Println(err)
return
}
if fileInfo.Mode().IsDir() {
fmt.Println("It is a directory")
} else {
fmt.Println("It is a file")
}
}
輸出
It is a file
示例 4
在這個示例中,我們將使用 isRegular() 方法來查詢使用者提供的檔案是檔案還是目錄。
package main
import (
"fmt"
"os"
)
func main() {
// Replace this with the path to your file
file := "C:/Users/LENOVO/Desktop/go"
fileInfo, err := os.Stat(file)
if err != nil {
fmt.Println(err)
return
}
if fileInfo.Mode().IsRegular() {
fmt.Println("It is a file")
} else {
fmt.Println("It is a directory")
}
}
輸出
It is a directory
結論
我們已經成功編譯並執行了一個 Go 語言程式,用於檢查給定檔案是檔案還是目錄,並附帶示例。這裡我們使用了四種不同的方法來檢查結果。在第一個和第二個程式中,我們使用了 isDir() 和 lstat() 函式,而在第三個和第四個程式中,我們分別使用了 stat() 和 IsRegular() 函式。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP