2

I am using the following code to write in a file.

fileName = [[NSBundle mainBundle] pathForResource: @"user" ofType: @"txt"];
NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:fileName];
[myHandle seekToEndOfFile];

NSData *dataName = [uname dataUsingEncoding: NSUnicodeStringEncoding];

if ([dataName writeToFile:fileName atomically:YES])
    NSLog(@"writeok");

[myHandle seekToEndOfFile];

It overwrites the file. Suppose the file already contains the string "box". Now when I write a new word, "Hello", then the file contains only "Hello", not "box".

What is the problem with the code?

jscs
  • 63,694
  • 13
  • 151
  • 195
user426795
  • 11,073
  • 11
  • 35
  • 35
  • You should be using the - (void)writeData:(NSData *)data method of the NSFileHandle. i.e: [myHandle writeData: dataName]; – RichB Aug 25 '10 at 11:24

1 Answers1

2

You cannot write to files in the Bundle. As the Bundle is code signed, any attempt to change the files in the bundle would break the signing. You need to move the file to the Documents directory and work on it there.

RichB
  • 118
  • 3
  • Rich, Yes I am not writting it in bundle. The problem is that i want append in new line in the file. But it override the file. So, hw to append in the new line of a file? – user426795 Aug 25 '10 at 09:30
  • 1
    (The code above is writing to a file in the Bundle). The writeToFile:atomically:encoding:error: method above overwrites the file if it exists. You could either read the contents of the file first, append to that string what you want and write it back as above or as you say use NSFileHandle. – RichB Aug 25 '10 at 09:47