itsaboutcode
itsaboutcode

Reputation: 25109

Getting Current Directory in Objective C

I am trying to get current directory, but its giving me path of DEBUG folder, how i can get the path of current directory. I am using the following code.

NSFileManager *filemgr;
NSString *currentpath;

filemgr = [[NSFileManager alloc] init];

currentpath = [filemgr currentDirectoryPath];

Upvotes: 24

Views: 25440

Answers (3)

PLG
PLG

Reputation: 468

When getting paths for a service loaded via launchd, the paths can be very different.

NSLog(@"argv: %s", argv[0]);
NSLog(@"NSProcessInfo: %@", NSProcessInfo.processInfo.arguments[0]);
NSLog(@"currentDirectoryPath: %@", [[NSFileManager defaultManager] currentDirectoryPath]);
NSLog(@"PWD: %@", [[NSProcessInfo processInfo] environment][@"PWD"]);

Output:

argv: /Users/dev/.ioi/default-runtime-manager/default-runtime-manager
NSProcessInfo: /Users/dev/.ioi/default-runtime-manager/default-runtime-manager
currentDirectoryPath: /Users/dev/Library/Application Support/IOI/default-runtime-manager
PWD: (null)
  • NSProcessInfo gives the location where the executable was found.
  • currentDirectoryPath returns the WorkingDirectory specified in the launchd plist.

The answer to getting the executable path was found here: StackOverflow: NSProcessInfo. The other paths were from: @lupdidup

Upvotes: 2

lupdidup
lupdidup

Reputation: 311

Developing further on that. The current working directory and launch directory may be different! Take this example, the app is launched from the home directory (~).

Library/Developer/Xcode/DerivedData/MyApp-ehwczslxjxsxiob/Build/Products/Debug/MyApp.app/Contents/MacOS/MyApp -param value
NSString *p1 = [[NSFileManager defaultManager] currentDirectoryPath];
// p1 = ~/Library/Containers/com.MyApp.beta/Data
NSString *p2 = [[NSProcessInfo processInfo] environment][@"PWD"];
// p2 = ~

Depending on the situation you might want one or the other. In my case I want to provide a CLI which takes path arguments that may be relative to the current working directory in the shell.

Upvotes: 2

mipadi
mipadi

Reputation: 411202

currentDirectoryPath returns the current working directory of the program. If you launch it from Xcode in Debug mode, the current directory of the program is the Debug directory.

Upvotes: 27

Related Questions