Search code examples
objective-cc-libraries

Load file to NSData with C


Problem is to load image file to UIImage. Original file cashed in file system and managed by C-library (question about it).

With objective-C I can do so:

NSData *file = [NSData dataWithContentsOfFile:...];
[UIImage imageWithData:file];

But how it possible to load file data to objective-C with C?

With C I can open file this like:

ret = fopen( name, options);

But can I use the ret ptr to init NSData:

[NSData dataWithBytesNoCopy:ret length:length_of_ret];?

Thanks a lot for any help!


Solution

  • Read bytes from file using fread.

    FILE * ret = fopen( name, options);
    void *data = malloc(bytes);
    fread(data, 1, bytes, ret); 
    fclose(ret);
     NSData *data = [NSData dataWithBytesNoCopy:data length:bytes];