Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I guess <strong>Hot Licks</strong> is right, you probably want to simply use <code>-[NSData dataWithContentsOfFile:]</code>, but in the case you want to use C level APIs, you can do:</p> <pre><code>#define MY_BUFFER_SIZE 1024 FILE * fd = fopen(c_sd_url, "rb"); NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; char buffer[MY_BUFFER_SIZE]; if (fd) { fcntl(fd, F_GLOBAL_NOCACHE, 1); // if you can predict the capacity it's better for performance NSMutableData* myData = [NSMutableData dataWithCapacity:1024]; while(fgets(buffer, MY_BUFFER_SIZE, fd) != NULL) { [myData appendBytes:buffer length:strlen(buffer)]; } } // use your 'myData' [pool release]; </code></pre> <p><strong>Updated:</strong> to avoid useless copy of <code>buffer</code> data, and following <strong>H2CO3</strong>'s comment:</p> <p>It's better to avoid to write data to a buffer and then copy it to the NSMutableData, we can use <code>-[NSData mutableBytes]</code> to access directly the underlying C structure. Also, <strong>H2CO3</strong> is completely right, using <code>fread</code> is much better since it gives us the length of the bytes read.</p> <pre><code>#define MY_BUFFER_SIZE 1024 FILE * fd = fopen(c_sd_url, "rb"); if (fd) { fcntl(fd, F_GLOBAL_NOCACHE, 1); // if you can predict the capacity it's better for performance NSMutableData* myData = [[NSMutableData alloc] init]; while(YES) { // store the length before addition NSUInteger previousLength = [myData length]; // increase the length so we can write more bytes [myData increaseLengthBy:MY_BUFFER_SIZE]; // read bytes from stream directly at the end of our data size_t len = fread([myData mutableBytes] + previousLength, 1, MY_BUFFER_SIZE, fd); // set data length [myData setLength:previousLength + len]; // if end-of-file exit the loop if (len == 0) { break; } } // use your 'myData' NSLog(@"myData: %@", [[NSString alloc] initWithData:myData encoding:NSASCIIStringEncoding]); [myData release]; } </code></pre> <p>If you want to have a <code>\0</code> terminated NSData, just add at the end:</p> <pre><code>[myData appendBytes:"\0" length:1]; </code></pre> <p>Good luck ;)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload