Locksleyu
Locksleyu

Reputation: 5355

Error 13 (Permission Denied) when running open on file I created (iOS)

I have a simple program running on iOS (iPad) which opens a file, writes some data, closes the file, and then tries to reopen the file. The strange thing is that the second open sometimes fails with return code -1 and errno 13 (Permission Denied). If I run the code several times it will alternately fail and succeed (the pattern seems random).

Below is the code I am using, can anyone explain what I am doing wrong? The first open always succeeds and the write also always succeeds.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"file.txt"];

result = remove([appFile cStringUsingEncoding:NSASCIIStringEncoding]);

int fp = open([appFile cStringUsingEncoding:NSASCIIStringEncoding], O_RDWR | O_CREAT);
result = write(fp, "abc", 3);
close(fp);

fp = open([appFile cStringUsingEncoding:NSASCIIStringEncoding], O_RDONLY);
NSLog(@"fp = %i, errno = %i", fp, errno);
close(fp);

Upvotes: 3

Views: 10970

Answers (2)

leesagacious
leesagacious

Reputation: 322

Open file folder must have executable permissions, so use:

chmod 0760 "dir"

Upvotes: 0

ott--
ott--

Reputation: 5722

From the manpage for open(2):

The oflag argument may indicate that the file is to be created if it does
not exist (by specifying the O_CREAT flag). In this case, open requires a
third argument mode_t mode;

As you do not specify the 3rd argument, it will use a random value, that's why it fails sometimes. Add a 3rd parameter 0644, then it will always work.

Upvotes: 3

Related Questions