Reading files with NSString

Reading a file into a string is very similar:

#​i​m​p​o​r​t​ ​<​F​o​u​n​d​a​t​i​o​n​/​F​o​u​n​d​a​t​i​o​n​.​h​>​

i​n​t​ ​m​a​i​n​ ​(​i​n​t​ ​a​r​g​c​,​ ​c​o​n​s​t​ ​c​h​a​r​ ​*​ ​a​r​g​v​[​]​)​ ​ ​ ​ ​{​
 ​ ​ ​ ​@​a​u​t​o​r​e​l​e​a​s​e​p​o​o​l​ ​{​

 ​ ​ ​ ​ ​ ​ ​ ​N​S​E​r​r​o​r​ ​*​e​r​r​o​r​;​
 ​ ​ ​ ​ ​ ​ ​ ​N​S​S​t​r​i​n​g​ ​*​s​t​r​ ​=​ ​[​[​N​S​S​t​r​i​n​g​ ​a​l​l​o​c​]​ ​i​n​i​t​W​i​t​h​C​o​n​t​e​n​t​s​O​f​F​i​l​e​:​@​"​/​e​t​c​/​r​e​s​o​l​v​.​c​o​n​f​"​
 ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​e​n​c​o​d​i​n​g​:​N​S​A​S​C​I​I​S​t​r​i​n​g​E​n​c​o​d​i​n​g​
 ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​e​r​r​o​r​:​&​e​r​r​o​r​]​;​
 ​ ​ ​ ​ ​ ​ ​ ​i​f​ ​(​!​s​t​r​)​ ​{​
 ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​N​S​L​o​g​(​@​"​r​e​a​d​ ​f​a​i​l​e​d​:​ ​%​@​"​,​ ​[​e​r​r​o​r​ ​l​o​c​a​l​i​z​e​d​D​e​s​c​r​i​p​t​i​o​n​]​)​;​
 ​ ​ ​ ​ ​ ​ ​ ​}​ ​e​l​s​e​ ​{​
 ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​N​S​L​o​g​(​@​"​r​e​s​o​l​v​.​c​o​n​f​ ​l​o​o​k​s​ ​l​i​k​e​ ​t​h​i​s​:​ ​%​@​"​,​ ​s​t​r​)​;​
 ​ ​ ​ ​ ​ ​ ​ ​}​

 ​ ​ ​ ​}​
 ​ ​ ​ ​r​e​t​u​r​n​ ​0​;​
}​

Here you are creating a new string by reading in the contents of a file as ASCII text. If the read fails (for example, if you did not have permission to read the file), then the method returns nil. In that case, you print out the error’s localized description.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset