如何获取和设置正确的电流路径

时间:2014-05-29 10:44:18

标签: objective-c nsstring foundation

在我的简单命令行程序中,我尝试将字符串写入文本文件

[str writeToFile:@"myfile.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];

当我通过finder运行我的exec文件时,我希望" myfile.txt"在exec文件所在的文件夹中创建,但它是在" / users / me"

中创建的

后来我尝试通过这些代码获取我的程序的当前路径

NSFileManager *filemgr;
NSString *currentpath;
filemgr = [[NSFileManager alloc] init];
currentpath = [filemgr currentDirectoryPath];
NSLog(@"Current path is : %@",current path);

我发现无论我的exec文件的位置如何,当前路径始终是" / users / me"。有没有办法找到正确的道路?

1 个答案:

答案 0 :(得分:0)

您可以使用defaultManager NSFileManager方法返回的实例来操纵您当前的路径:

NSString *currentpath = [[NSFileManager defaultManager] currentDirectoryPath];

[[NSFileManager defaultManager] changeCurrentDirectoryPath:@"/new/path/"];

您可以从捆绑包的bundlePath方法获取可执行文件的路径:

NSString *path = [[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent];