Steven Fisher
Steven Fisher

Reputation: 44886

How do I tell if a file is contained in a directory?

What's the right way to tell if a file is contained within a given directory, or a subdirectory thereof?

I want something like:

if ([directoryPath contains: filePath]) {
    // file is in directory, or in a subdirectory of directory.
}

Example:

ContainerPath: /Users/sfisher/Library/Application Support/iPhone Simulator/5.1/Applications/89A57CCB-250D-4D10-B913-EA456004B431/AppName.app

Not matching: /Users/sfisher/Library/Application Support/iPhone Simulator/5.1/Applications/89A57CCB-250D-4D10-B913-EA456004B431/Documents/db/Sample Data

Matching: /Users/sfisher/Library/Application Support/iPhone Simulator/5.1/Applications/89A57CCB-250D-4D10-B913-EA456004B431/AppName.app/Samples/1

I could convert everything to strings (including appending a "/" to the container directory) and check for a string match, but it seems there should be a built-in method for this.

Upvotes: 0

Views: 90

Answers (2)

Rob Napier
Rob Napier

Reputation: 299633

In principle, your underlying desire is surprising impossible. A given file path may include through symbolic or hard links, making "containment" a very complicated question. These kinds of links are uncommon in iOS, but iOS is still Unix, and in Unix such things are legal.

So your real question is actually whether one path specifier (string) is contained in another. So checking the paths as strings is the correct approach.

Upvotes: 1

Lily Ballard
Lily Ballard

Reputation: 185841

I think a simple string match is the right way to do it:

if (![directoryPath hasSuffix:@"/"]) directoryPath = [directoryPath stringByAppendingString:@"/"];
if ([filePath hasPrefix:directoryPath]) {
    // ...
}

Note that this doesn't deal with complications introduced by symlinks, or with relative paths.

Upvotes: 1

Related Questions