Using nsdata to read and write binary files

Source: Internet
Author: User
Reference Article : Http://blog.codingmylife.com /? P = 85
# Import <Foundation/Foundation. h> int main (INT argc, const char * argv []) {ngutoreleasepool * Pool = [[ngutoreleasepool alloc] init]; nsstring * Path = @ "/users/billchen/desktop/f1.rtf"; nsstring * temp = @ "Hello Friend"; int I = 100; float F = 98.3333f; nsmutabledata * Writer = [[nsmutabledata alloc] init]; [Writer appenddata: [temp datausingencoding: nsutf8stringencoding]; [Writer appendbytes: & I length: sizeof (I)]; // & indicates the access address [Writer appendbytes: & F length: sizeof (f)]; [Writer writetofile: path atomically: Yes]; [Writer release]; int II; float ff; nsstring * ttemp; nsdata * reader = [nsdata datawithcontentsoffile: path]; ttemp = [[nsstring alloc] initwithdata: [READER subdatawithrange: nsmakerange (0, [temp length])] encoding: nsutf8stringencoding]; [READER getbytes: & II Range: nsmakerange ([temp length], sizeof (ii)]; [READER getbytes: & FF range: nsmakerange ([temp length] + sizeof (II), sizeof (ff)]; nslog (@ "string :%@ INT: % I float: % F ", ttemp, II, ff); [temp release]; [ttemp release]; [path release]; [pool drain]; return 0 ;}
    • & Used to retrieve addresses and pointers
    • Nsmakerange is used to generate the nsange

Returned results:

 
[Switching to process 13606 Thread 0x0] 13:24:04. 962 demo09 [13606: 903] string: Hello friend INT: 100 float: 98.333298

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.