Apple Swift File I / O

I am looking for Swift I / O for short presentations at my university next week. I really did not find anything about this.

Here are the operations I found:

let location = "/Users/test/test.txt" var str = "Hello, playground" //write str.writeToFile( location, atomically: false, encoding: NSUTF8StringEncoding, error: nil) //read let filecontent = String(contentsOfFile: location, encoding: NSUTF8StringEncoding, error: nil) //binary read let test = NSData(contentsOfFile: location) //if file exists NSFileManager().fileExistsAtPath(location) //find Files in the App Bundle with suffix test and prefix txt var path= NSBundle.mainBundle().pathForResource("test", ofType: "txt") //path for dynamic user names if let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] { let path = dirs[0].stringByAppendingPathComponent( "file.txt") //printout: /Users/test/Documents/file.txt 

Is there an operation with which I can read single characters?
Can I add text to a file? Can I write / read only a line?
Are there any other file operations I need to know there?

+6
source share
1 answer

Is there an operation with which I can read single characters?

Swift code can use any of the usual frameworks (Foundation, Cocoa, Cocoa Touch, etc.), and this in itself gives you many ways to read and write files, usually at a higher level than character at a time. If you want to use the input / output of lower level files, you can use NSInputStream and NSOutputStream , as Martin R. suggests, or you can use NSData .

Of course, you can also use all the usual C stdio functions if you really want to plunge into your files. But when you work with objects, it usually makes no sense to work at such a low level.

+2
source

Source: https://habr.com/ru/post/978209/


All Articles