Saturday, April 27, 2013

NSFileHandle writeData example ios


writeData:

Synchronously writes the specified data to the receiver.
- (void)writeData:(NSData *)data
Parameters
data
The data to be written.
Discussion of [NSFileHandle writeData]
If the receiver is a file, writing takes place at the file pointer’s current position. After it writes the data, the method advances the file pointer by the number of bytes written. [NSFileHandle writeData]This method raises an exception if the file descriptor is closed or is not valid, if the receiver represents an unconnected pipe or socket endpoint, if no free space is left on the file system, or if any other writing error occurs.

Example of [NSFileHandle writeData]

Write to file.
----------------------------------------------------------------------------
NSString *testFile = @"/test.txt";
NSFileHandle * file = [NSFileHandle fileHandleForWritingAtPath:testFile];
[file seekToFileOffset:30]; 
NSLog(@"offset : %llu", [file offsetInFile]); 

NSData *databuffer = [file readDataOfLength:10];
[file seekToFileOffset:50]; 
[file writeData :databuffer];

[file closeFile]; 

----------------------------------------------------------------------------
- (NSString *)outputFromExporter:(COExporter *)exporter input:(NSString *)input {
  NSString *exportedString = nil;
  NSString *path = [exporter path];
  NSTask *task = [[NSTask alloc] init];

  NSPipe *writePipe = [NSPipe pipe];
  NSFileHandle *writeHandle = [writePipe fileHandleForWriting];
  NSPipe *readPipe = [NSPipe pipe];
  NSFileHandle *readHandle = [readPipe fileHandleForReading];

  NSMutableData *outputData = [[NSMutableData alloc] init];
  NSData *readData = nil;

  // Set the launch path and I/O for the task
  [task setLaunchPath:path];
  [task setStandardInput:writePipe];
  [task setStandardOutput:readPipe];

  // Launch the exporter, it will convert the raw OPML into HTML, Plaintext, etc
  [task launch];

  // Write the raw OPML representation to the exporter's input stream
  [writeHandle writeData:[input dataUsingEncoding:NSUTF8StringEncoding]];
  [writeHandle closeFile];

  while ((readData = [readHandle availableData]) && [readData length]) {
    [outputData appendData:readData];
  }

  exportedString = [[NSString alloc] initWithData:outputData encoding:NSUTF8StringEncoding];
  return exportedString;
}