Change Infos Header and Write It Back

I need to change the file header information in the document folder. What is the most recommended way to read and write binary data?

  • How to read data from a binary document folder to an array / stream
  • How to write data from an array / stream to a local iPad iPad folder?

Binary reading / writing in objective-c

+3
source share
3 answers

It is difficult to answer unless you are more specific, but the most effective way to do this is to probably not modify the file at all.

iOS, , . , / , (, iTunes iPhoto do) ?

, C : NSInputStream NSOutputStream, .

, , API:

typedef void (^DataExportHandler)(NSData *resultData, NSError *exportError);

@interface DataStore (FileExport)

/** If you wanted to abort the export, you could pass the stream into the `abort…:`-method
@param  identifier  Something that you use internally to manage your stored files.
@param  error       For good measure…
@return The export stream for the object or `nil` if an error occurred.
*/
- (NSInputStream *)exportStreamForObjectWithIdentifier:(id)identifier error:(NSError * __autoreleasing*)error;

/** If your data are mostly small, it may be more convenient to not consume the exports as streams but as BLOBs, if the sizes vary you could implement this as a convenience…
@param  identifier  Equivalent to the identifier in the method above
@param  handler     Callback that is invoked once some time later when the export finished or failed. **Must not** be `nil`.
*/
@return A cancellation token.
- (id)asynchronouslyExportDataForObjectWithIdentifier:(id)identifier resultHandler:(DataExportHandler)handler;

/**
@param  exportToken  Either a stream from the first method or a token returned from the second one.
*/
- (void)abortAsynchronousExportWithToken:(id)exportToken;

@end

, ARC , , , .

, : rawDataStream, youd , . , , , Ive , NSStreamDelegate .

, ...

/// Scribble of another helper class that can be used whenever one needs to consume a stream for its aggregate data:
@interface _StreamConsumer : NSObject <NSStreamDelegate> {
    NSInputStream *_stream;
    DataExportHandler _handler;
    NSMutableData *_data;
}

// initiate the data, set itself as the stream’s delegate, open and schedule the stream in a runloop.
- (id)initWithInputStream:(NSInputStream *)stream resultHandler:(DataExportHandler)handler;

// forward the close to the stream
- (void)close;

// Implementation of the stream delegate callbacks can be more or less copy-pasted from Apple’s Stream Programming Guide (https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Streams/Streams.html)
@end

@implementation DataStore (FileExport)

- (id)asynchronouslyExportDataForObjectWithIdentifier:(id)someUniqueIdentifier resultHandler:(void (^)(NSData *fileData, NSError *exportError))
{
    NSParameterAssert(handler);
    handler = [handler copy];

    NSError *setupError;
    NSInputStream *exportStream = [self exportStreamForObjectWithIdentifier:someUniqueIdentifier error:&setupError];
    if (!exportStream)
    {
        dispatch_async(dispatch_get_current_queue(), ^{
            handler(nil, setupError);
        });

        return nil;
    }

    _StreamConsumer *helper = [[_StreamConsumer alloc] initWithStream:exportStream resultHandler:handler];

    return helper;
}

- (void)abortAsynchronousExportWithToken:(id)exportToken
{
    [exportToken close];
}

- (NSInputStream *)exportStreamForObjectWithIdentifier:(id)identifier error:(NSError * __autoreleasing*)error
{
    // do your thing to retrieve the URL to the actual data-file and then:
    NSInputStream *rawDataStream = [NSInputStream inputStreamWithURL:rawFileURL];

    if (!rawDataStream)
    {
        // populate the error in a meaningful way
        return nil;
    }

    CFReadStream cfExportStream;
    CFWriteStream cfBuffer;
    CFStreamCreateBoundPair(kCFAllocatorDefault, &cfExportStream, &cfBuffer, someValueYouHaveTuned);

    if (!cfExportStream || !cfBuffer)
    {
        // error population
        return nil;
    }

    NSInputStream *exportStream = (__bridge_transfer NSInputStream *)cfExportStream;

    // HACKITY HACK: In reality, you’d want this stuff separated!
    // For the sake of simplicity, take the responsibility for that ourselves
    _exportBuffer = (__bridge_transfer NSOutputStream *)cfBuffer;

    rawDataStream.delegate = self;
    [rawDataStream open];
    [rawDataStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunloopDefaultMode];
    // END: HACKITY HACK

    return exportStream;
}

@end
+3

- , .
.

NSString *path= [[NSBundle mainBundle] pathForResource:@"myFile" ofType:@"txt"];


, 1 10 .
, - , , , , . 2, 3 7 - 1 10. , , .
, - , .
, , .

+3

C : FILE*, fopen, fseeko, fread, fwrite.

if your data is only 266 bytes, it’s small enough that you can just read it all in use [NSMutableData dataWithContentsOfURL:url]and then write it back (overwrite the entire file) using methods NSData write*. however, you will want to avoid this approach with large files. in which case you want to use the C-interface (see. above) or consider NSFileHandle, NSInputStream, NSOutputStream, CFReadStream, CFWriteStream, etc.

+1
source

All Articles