0

I have a .txt file with a small password in it. I would like to change that file's text. How can I do that? I can get the file's text using :

 NSString *passWord = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"password" ofType:@"txt"] encoding:NSUTF8StringEncoding error:NULL];

But I can't seem to find a way to replace the contents of the file with a string.

XtremeHek3r
  • 381
  • 2
  • 16

1 Answers1

1

The way to do this is to remove old file and create new one. Removing existing file

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

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"myFile.txt"];

NSFileManager *fileManager = [NSFileManager defaultManager];

if([fileManager fileExistsAtPath:filePath])
{
    [fileManager removeItemAtPath:filePath error:&error];
}

To crate new file with your new password write password data while creating file as:

[createFileAtPath:path contents:[NSData data] attributes:nil]
Nirmal Choudhari
  • 559
  • 5
  • 17
  • How does your code actually write the string to a file? – rmaddy Feb 16 '15 at 06:41
  • @Nirmal Choudhari Can't I just use the `[[NSBundle mainBundle] pathForResource:@"password" ofType:@"txt"] encoding:NSUTF8StringEncoding error:NULL];` for the path? – XtremeHek3r Feb 16 '15 at 06:43
  • 2
    @XtremeHek3r No. As I said, the bundle is read-only. You can't write to it. – rmaddy Feb 16 '15 at 06:47
  • No You have to copy file from your bundle to document directory after app install to work this. You can read file from main bundle but cant write them. thats why. – Nirmal Choudhari Feb 16 '15 at 06:56
  • @XtremeHek3r i think This like helpful for u http://stackoverflow.com/questions/19351535/saving-text-file-to-documents-directory-in-ios-7 – Ilesh P Feb 16 '15 at 07:01
  • This is the answer I was looking for. I thought I could write data to the txt file in the project but I guess not. Well anyway, I decided to re-do my project and write a file to Documents directory instead. – XtremeHek3r Feb 18 '15 at 17:47