简体   繁体   中英

write nsdata in a file at a specific position

I have the following code for writing data in a file:

NSData *chunk=...; //some data
 NSArray *docDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [docDirectories objectAtIndex:0];
    NSString *fileName   = [docDirectory stringByAppendingPathComponent:@"TestFile.txt"];
 [chunk writeToFile:fileName atomically:NO];

If I know the size of the file (let;s say 10*chunk) and if i also receive the position of each chunk in the total length of the file, how can I add write data to file at that specific position?

To solve your questions, your best bet is to use NSOutputStream , it makes operations like these easier to handle.

That being said, you would append to the end of the file like this:

NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:filePath append:YES];
[stream open];
NSData *chunk = ...; // some data
[stream write:(uint8_t *)[chunk bytes] maxLength:[chunk length]];
[stream close];
// remember to always handle memory (if not using ARC) //

To insert a chunk of data in the middle of a file is somewhat more involved:

NSData *chunk = ...; // some data
NSString *filePath = ... ; // get the file //
NSUInteger insertionPoint = ...; // get the insertion point //
// make sure the file exists, if it does, do the following //
NSData *oldData = [NSData dataWithContentsOfFile:filePath];
// error checking would be nice... if (oldData) ... blah //
NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:filePath append:NO];
[stream open];
[stream write:(uint8_t *)[oldData bytes] maxLength:insertionPoint]; // write the old data up to the insertion point //
[stream write:(uint8_t *)[chunk bytes] maxLength:[chunk length]]; // write the new data //
[stream write:(uint8_t *)&[oldData bytes][insertionPoint] maxLength:[oldData length] - insertionPoint]; // write the rest of old data at the end of the file //
[stream close];
// remember to always handle memory (if not using ARC) //

Disclaimer: Code written in browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM