Objective-C File Access

Source: Internet
Author: User

Generally, there are two methods for file access. These two methods are mainly divided based on the file content. A file composed of text can be read and written using characters, while other types of files are usually stored in the form of bytecode (of course, we can also use bytecode to store text ).

In OC, The NSString class can directly call internal methods to read and write strings. Unlike java, I/O Stream classes are used for a series of encapsulation. In addition, OC text access is very simple. For example, you can use the following lines to write specific text files:

# Pragma writes data to the file using NSString: NSError * error = nil; NSMutableString * str = [[NSMutableString alloc] init]; for (int I = 0; I <10; I ++) {[str appendString: @ "Hello! Hello \ n "];} if ([str writeToFile: @"/tmp/my.txt "atomically: YES encoding: NSUTF8StringEncoding error: & error]) {NSLog (@ "success");} else {NSLog (@ "error: % @", [error localizedDescription]);}

Reading is also rare:

# Pragma reads data from a file using NSString: NSError * error = nil; NSString * str = [[NSString alloc] initWithContentsOfFile: @ "/tmp/my.txt" encoding: NSUTF8StringEncoding error: & error]; if (str) {NSLog (@ "content: % @", str);} else {NSLog (@ "error: % @", [error localizedDescription]);}
What then?

When using NSData, I was even more shocked to understand the unique simplicity of Objective-C, and obviously had great advantages in java/c ++, python/php is simple and clear.

There are several lines of code to read and write NSData files.

# Pragma uses NSData to access NSError * error = nil; NSData * data = [[NSData alloc] initWithContentsOfFile: @ "/tmp/my.txt"]; if ([data writeToFile: @ "/tmp/my2.txt" options: NSDataWritingAtomic error: & error]) {NSLog (@ "success");} else {NSLog (@ "error: % @", error );}



Related Article

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.