2

我试图直接打开一个文件fopen("/test.txt","w+");它适用于模拟器,但不适用于 iPhone。

然后我试过这个:

NSString *path = [[NSBundle mainBundle] pathForResource: @"GirlName.txt" ofType:nil];
NSLog(path);
fichier = fopen([path cStringUsingEncoding:1],"w+");

if (fichier != NULL)
{
    ...
}
else
{
    perror("error ");
}

我在控制台中收到权限被拒绝:

2009-07-24 17:17:27.415 Mademoiselle[897:20b]
/var/mobile/Applications/.../....app/GirlName.txt
error : Permission denied

你能告诉我有什么问题吗?

4

1 回答 1

5

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];
}
于 2009-07-24T15:46:57.690 回答