iPhone unix文件访问

时间:2012-01-19 09:45:58

标签: iphone file permissions

当我使用时:

int fd = open(fileNameWitPath, O_CREAT | O_RDWR);
设备模拟器中的

都是对的。 但物理设备返回 fd = -1 errno = 0x0d(13),权限被拒绝。

目标路径是应用程序沙箱文档或tmp路径。

这是否可以阅读&通过Unix函数在iPhone上,在应用程序专用区域中写入文件而不越狱?

4 个答案:

答案 0 :(得分:2)

它应该可以正常工作但你必须记住,iOS模拟器使用的文件系统与真实设备不同。事实上,您只能从捆绑中读取文件,而不是WRITE,并且您尝试使用读取/写入权限打开。请检查 fileNameWitPath

的值

获取文档目录的正确方法是:

NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

你应该使用

NSFileManager *fileManager = [NSFileManager defaultManager]; 
[fileManager createFileAtPath: contents: attributes:]

而不是

int fd = open(fileNameWitPath, O_CREAT | O_RDWR);

答案 1 :(得分:2)

Skippy关于缺少第三个参数的评论是正确的问题。

如果没有第三个参数,open(...)将在第一次运行,并且在后续运行时失败并显示-1和EACCES,因为应用程序是第一次创建文件,但不再具有访问该文件的权限。 (如果您正在重新编译和测试设备,并查看错误,那么因为您需要删除删除了错误许可文件的应用程序。)

答案 2 :(得分:0)

* 完成对答案的重写*

以下代码有效:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    NSArray *dp = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *path = [dp objectAtIndex:0];
    NSString *fileNameWithPath = [NSString stringWithFormat:@"%@/%@",path,@"fileName.txt"];
    int fd = open([fileNameWithPath UTF8String], O_CREAT | O_RDWR);

    NSLog(@"Open %@ for writing returned %d",fileNameWithPath,fd);

    return YES;
}

调试输出:

Re-enabling shared library breakpoint 1
(gdb) n
30      NSLog(@"Open %@ for writing returned %d",fileNameWithPath,fd);
(gdb) n
2012-01-20 11:01:23.161 FOpen[6535:707] Open /var/mobile/Applications/AF7EA358-E4AA-491F-AEA1-83080F2749E5/Documents/fileName.txt for writing returned 6
32      return YES;

关键是你必须传递c函数'open'一个c风格的字符串,例如[fileNameWithPath UTF8String]。如果你正在使用ARC,你可能需要做更多的工作来让编译器满意,但我无法确认。

答案 3 :(得分:0)

我写道:

int fd = open(fileNameWithPath, O_CREAT | O_RDWR);

但是“调用'打开'需要在设置'O_CREAT'时使用第三个参数”。 代码行必须是(对于RW权限):

 int fd = open(fileNameWithPath, O_CREAT | O_RDWR, 0x0666);

这很好。

[编辑] 我写道:

int fd = open(fileNameWithPath, O_CREAT | O_RDWR, 0x0666);

这是错误,umask必须是666但是八进制,而不是十六进制:

int fd = open(fileNameWithPath, O_CREAT | O_RDWR, 00666);