Catcoder
Catcoder

Reputation: 33

Check if a file extension does not exist in a directory using Go

I am trying to check if a directory does not have a file with a ".rpm" extension. I will not know what the filename is beforehand and each directory will have multiple files.

Here is my code:

import {
    "fmt"
    "os"
    "path/filepath"
}

func main() {
    dirname := "." + string(filepath.Separator)

    d, err := os.Open(dirname)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    defer d.Close()

    files, err := d.Readdir(-1)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    fmt.Print("\n" + "Reading " + dirname)

    for _, file := range files {
        if file.Mode().IsRegular() {
            // TODO: if rpm file not present, print no rpm file found
            if filepath.Ext(file.Name()) == ".rpm" {
                fmt.Println(file.Name() + "\n")
                f, err := os.Open(file.Name())
                if err != nil {
                    panic(err)
                }
            }
        }
    }
}

The code above will open any .rpm files within the current directory.

I want to check for the following: if a ".rpm" file does not exist the list of files of the current directory, then print "rpm does not exist" and os.Exit.

I've tried this code:

if filepath.Ext(file.Name()) != ".rpm" {
    fmt.Println("no rpm found")
}

and I've tried using

if filepath.Ext(file.Name()) == ".rpm" {
    ... *code above* ...
} else {
    fmt.Println("ERR: RPM file does not exist")
}

I'm running into the error where if other files are present without the extension of .rpm, then it will prompt the error.

How can I go about doing this without having the filename beforehand?

Upvotes: 2

Views: 1155

Answers (2)

J-Jacques M
J-Jacques M

Reputation: 1118

Try this

...
splitted := strings.Split(file.Name(), ".")
lenSplit := len(splitted)
if lenSplit > 1 && splitted[lenSplit-1] == "rpm" {
  // file with extension
}
...
  1. Split filename by "."
  2. Go to the last string in the array of string
  3. Check if the last string match "rpm"

Upvotes: 0

icza
icza

Reputation: 417777

Whether none of the files have .rpm extension cannot be told in any single iteration. You can only tell that for certain after checking all files.

So instead of trying to squeeze that into the loop, maintain a found variable which you may update when an .rpm file is found.

found := false // Assume false for now
for _, file := range files {
    if file.Mode().IsRegular() {
        if filepath.Ext(file.Name()) == ".rpm" {
            // Process rpm file, and:
            found = true
        }
    }
}

if !found {
    fmt.Println("rpm file not found")
}

If you only need to process 1 .rpm file, then the "state" management (the found variable) will not be necessary. You can return if you found and processed an .rpm file, and if you get to the end of the loop, you'll know there wasn't any rpm file:

for _, file := range files {
    if file.Mode().IsRegular() {
        if filepath.Ext(file.Name()) == ".rpm" {
            // Process rpm file, and:
            return
        }
    }
}

// We returned earlier if rpm was found, so here we know there isn't any:
fmt.Println("rpm file not found")

Upvotes: 1

Related Questions