0

I managed to read and write data into a file in swift. But i'd like to append file when I write data again into it, and also read the last 10 lines of the file. How can I do that?

This is the code i am using - reading:

 // Create a FileHandle instance

let file: NSFileHandle? = NSFileHandle(forReadingAtPath: "hello.swift")

if file != nil {
// Read all the data
let data = file?.readDataToEndOfFile()

// Close the file
file?.closeFile()

// Convert our data to string
let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(str!)
}
    else {
    print("Ooops! Something went wrong!")
    }

This is the code i am using - writing:

// Set the file path
let path = "myfile.txt"

// Set the contents
   let contents = "Here are my file's contents"
  do {
   // Write contents to file
  try contents.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
}
catch let error as NSError {
    print("Ooops! Something went wrong: \(error)")
}
Rashwan L
  • 38,237
  • 7
  • 103
  • 107
fr0zt
  • 733
  • 4
  • 12
  • 30

0 Answers0