iPhone - fopen and pathForResource - Permission denied
-
19-09-2019 - |
Question
I've tried to open a file directly like fopen("/test.txt","w+")
; it works on the simulator but doesn't work on the iPhone.
Then I've tried this:
NSString *path = [[NSBundle mainBundle] pathForResource: @"GirlName.txt" ofType:nil];
NSLog(path);
fichier = fopen([path cStringUsingEncoding:1],"w+");
if (fichier != NULL)
{
...
}
else
{
perror("error ");
}
I receive in console Permission denied:
2009-07-24 17:17:27.415 Mademoiselle[897:20b]
/var/mobile/Applications/.../....app/GirlName.txt
error : Permission denied
Can you tell me what's wrong?
Solution
You cannot open a file within the application bundle and make it writable ("w+").
This same code will likely work (I have not tested it) if you change the mode to "r"
If you need a writable text file, you need to place in in a writable directory, I'd do something like this:
//Method writes a string to a text file
-(void) writeToTextFile{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
documentsDirectory];
NSString *content = @"Test Copy Here";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow