0

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
iUser
  • 1,075
  • 3
  • 20
  • 49
  • How do you check nothing is appended? What did you see when you stepped trough the code above line-by-line; was all correct and not errors? What do you see after calling `synchronizeFile` or `closeFile`? – meaning-matters Jul 04 '18 at 15:53
  • Your logic for getting a path to the `Documents` folder is wrong. But using a file handle is probably how I would append to an existing file. – rmaddy Jul 04 '18 at 15:55
  • If I append only a string then it works fine. But I don't know what I need to change when want to append a file to another file. – iUser Jul 04 '18 at 15:56

1 Answers1

1

As rmaddy says, you are using the wrong code to get the documents directory. For that you should use code something like this:

guard let docsURL =  try? FileManager.default.url(for: .documentDirectory, 
                 in: .userDomainMask, 
                 appropriateFor: nil, 
                 create: true else { return }

Then you need code to read the file that you want to append and use write to append it:

let fileURL = docsURL.appendingPathComponent(fileName)

let urlToAppend = docsURL.appendingPathComponent(fileNameToAppend)

guard let dataToAppend = try ? Data.contentsOf(url: urlToAppend) else { return }

guard let fileHandle = FileHandle(forWritingTo: fileURL) else { return }

fileHandle.seekToEndOfFile()

fileHandle.write(dataToAppend)

(Skipping error handling, closing the file, etc.)

Duncan C
  • 128,072
  • 22
  • 173
  • 272