Search code examples
iosobjective-c

Where can I find the file that I created with writeToFile?


I used writeToFile to create input.txt file , but without this file in the path of the project I don't know how can I find it.

NSString* str2 = [NSString stringWithUTF8String:cstr];
[str2 writeToFile:@"input.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
NSString* str3 = [NSString stringWithContentsOfFile:@"input.txt" encoding:NSUTF8StringEncoding error:nil];

Solution

  • You need to add a path to your app Documents folder to your file:

    //get path to Documents 
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    //add path to you file name
    NSString *fileWithPath = [documentPath stringByAppendingPathComponent:@"input.txt"];
    //then write
    [str2 writeToFile:fileWithPath atomically:TRUE encoding:NSUTF8StringEncoding error:NULL];
    

    then you will be able to read it back using fileWithPath:

    NSString* str3 = [NSString stringWithContentsOfFile:fileWithPath encoding:NSUTF8StringEncoding error:nil];