ios - write nsdata in a file at a specific position -
ios - write nsdata in a file at a specific position -
i have next code writing info in file:
nsdata *chunk=...; //some info nsarray *docdirectories = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes); nsstring *docdirectory = [docdirectories objectatindex:0]; nsstring *filename = [docdirectory stringbyappendingpathcomponent:@"testfile.txt"]; [chunk writetofile:filename atomically:no];
if know size of file (let;s 10*chunk) , if receive position of each chunk in total length of file, how can add together write info file @ specific position?
to solve questions, best bet utilize nsoutputstream, makes operations these easier handle.
that beingness said, append end of file this:
nsoutputstream *stream = [[nsoutputstream alloc] inittofileatpath:filepath append:yes]; [stream open]; nsdata *chunk = ...; // info [stream write:(uint8_t *)[chunk bytes] maxlength:[chunk length]]; [stream close]; // remember handle memory (if not using arc) //
to insert chunk of info in middle of file more involved:
nsdata *chunk = ...; // info nsstring *filepath = ... ; // file // nsuinteger insertionpoint = ...; // insertion point // // create sure file exists, if does, next // nsdata *olddata = [nsdata datawithcontentsoffile:filepath]; // error checking nice... if (olddata) ... blah // nsoutputstream *stream = [[nsoutputstream alloc] inittofileatpath:filepath append:no]; [stream open]; [stream write:(uint8_t *)[olddata bytes] maxlength:insertionpoint]; // write old info insertion point // [stream write:(uint8_t *)[chunk bytes] maxlength:[chunk length]]; // write new info // [stream write:(uint8_t *)&[olddata bytes][insertionpoint] maxlength:[olddata length] - insertionpoint]; // write rest of old info @ end of file // [stream close]; // remember handle memory (if not using arc) //
disclaimer: code written in browser.
ios file-io nsdata writetofile
Comments
Post a Comment