我是 ios 新手,我有 10 个 1024 字节的块。这些块不按顺序排列。如果我知道块的数量,我如何将数据插入大小为 10*1024 的文件中?到目前为止,我有以下代码:
//method called when new chunk arrvies
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//create a file name to write the data to using the documents directory:
filePath = [NSString stringWithFormat:@"%@/example.txt",
documentsDirectory];
NSFileHandle *writeFile = [NSFileHandle fileHandleForWritingToURL:filePath error:nil];
[writeFile truncateFileAtOffset:10240*sizeof(Byte)];
如何使用 fseek 添加新数据?
我确实尝试使用以下代码:
if ((chunkNo == 0 )||(chunkNo == 10))
{
NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:filePath append:YES];
[stream open];
NSData *chunk = chunkContainer; // some data
[stream write:(uint8_t *)[chunk bytes] maxLength:[chunk length]];
[stream close];
}
else{
NSData *chunk = chunkContainer; // some data
NSUInteger insertPoint = chunkNo*1024; // get the insertion point //
// make sure the file exists, if it does, do the following //
NSData *oldData = [NSData dataWithContentsOfFile:filePath];
NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:filePath append:NO];
[stream open];
[stream write:(uint8_t *)[oldData bytes] maxLength:insertPoint]; // 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]+insertPoint) maxLength:([oldData length]-insertPoint)]; // write the rest of old data at the end of the file //
[stream close];
}
但是如果块的顺序不正确,结果文件并不完全正确。如果块的顺序正确,则结果文件将正确显示。