ios - create an empty file of specific size and write new data to specific position with fseek -
i new ios have 10 chunks of 1024 bytes. chunks not in order. if know number of chunk how can insert info in file of size 10*1024? far have next code:
//method called when new chunk arrvies nsarray *paths = nssearchpathfordirectoriesindomains (nsdocumentdirectory, nsuserdomainmask, yes); nsstring *documentsdirectory = [paths objectatindex:0]; //create file name write info using documents directory: filepath = [nsstring stringwithformat:@"%@/example.txt", documentsdirectory]; nsfilehandle *writefile = [nsfilehandle filehandleforwritingtourl:filepath error:nil]; [writefile truncatefileatoffset:10240*sizeof(byte)]; how add together new info using fseek?
i did seek utilize next code:
if ((chunkno == 0 )||(chunkno == 10)) { nsoutputstream *stream = [[nsoutputstream alloc] inittofileatpath:filepath append:yes]; [stream open]; nsdata *chunk = chunkcontainer; // info [stream write:(uint8_t *)[chunk bytes] maxlength:[chunk length]]; [stream close]; } else{ nsdata *chunk = chunkcontainer; // info nsuinteger insertpoint = chunkno*1024; // insertion point // // create sure file exists, if does, next // nsdata *olddata = [nsdata datawithcontentsoffile:filepath]; nsoutputstream *stream = [[nsoutputstream alloc] inittofileatpath:filepath append:no]; [stream open]; [stream write:(uint8_t *)[olddata bytes] maxlength:insertpoint]; // write old info insertion point // [stream write:(uint8_t *)[chunk bytes] maxlength:[chunk length]]; // write new info // [stream write:(uint8_t *)([olddata bytes]+insertpoint) maxlength:([olddata length]-insertpoint)]; // write rest of old info @ end of file // [stream close]; } but result file not correct, if chunks not in right order. if chunks in right order, result file correctly displayed.
example:
nsstring *filepath = [@"~/desktop/fhtest.txt" stringbyexpandingtildeinpath]; [[nsfilemanager defaultmanager] createfileatpath:filepath contents:[nsdata new] attributes:nil]; nsfilehandle *fh; nsdata *data1 = [@"test data" datausingencoding:nsutf8stringencoding]; fh = [nsfilehandle filehandleforupdatingatpath:filepath]; [fh writedata:data1]; [fh closefile]; nsdata *data2 = [@"more data" datausingencoding:nsutf8stringencoding]; fh = [nsfilehandle filehandleforupdatingatpath:filepath]; [fh seektofileoffset:100]; [fh writedata:data2]; [fh closefile]; note seektofileoffset:100 fill expand file necessary filling necessary 0x00 bytes.
to create file of specific size, in case 100 bytes:
unsigned long long size = 100; [[nsfilemanager defaultmanager] createfileatpath:filepath contents:[nsdata new] attributes:nil]; nsfilehandle *fh = [nsfilehandle filehandleforupdatingatpath:filepath]; [fh seektofileoffset:size-1]; [fh writedata:[@"\x00" datausingencoding:nsutf8stringencoding]]; [fh closefile]; ios nsdata fseek nsfilehandle nsoutputstream
No comments:
Post a Comment