I have two files, File1 & File2. I want to append File2 at the end of File1.
func writeToFile(content: String, fileName: String) {
let contentToAppend = content+"\n"
let filePath = NSHomeDirectory() + "/Documents/" + fileName
//Check if file exists
if let fileHandle = FileHandle(forWritingAtPath: filePath) {
//Append to file
fileHandle.seekToEndOfFile()
fileHandle.write(contentToAppend.data(using: String.Encoding.utf8)!)
}
else {
//Create new file
do {
try contentToAppend.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)
} catch {
print("Error creating \(filePath)")
}
}
}
I was using this function to add string at the end of file. I didn't find anything to append file at the end. Can any one help me here if I am missing anything.