MB41
MB41

Reputation: 584

How can I write to file without rewriting the same line?

I have a function that reads line by line from a file and saved it into a variable line. I am trying to make it so that it reads a line and writes it to another file. Reads the next line and adds that line to the file. I have this code:

if let readFileObj = ReadWriteManager(path: readFilePath!) {
        while let line = readFileObj.nextLine() {
            println(line)
        line.writeToFile(NSHomeDirectory().stringByAppendingPathComponent("Documents").stringByAppendingPathComponent("textfile.txt"), atomically: false, encoding: NSUTF8StringEncoding, error: nil)
        }
}

I have a class ReadWriteManager that takes the path of the file to be read. That class has a function nextLine() that returns the next line of the file as a string. When I do println, my console output screen shows all of the file content. Unfortunate when I try to write it to a file textfile.txt using .writeToFile(), it keeps rewriting the same line over and over again. So when I check to see if the files successfully copied, it only shows the last line of the file that was read. How can I make it so that it'll write a line then write to the next line without rewriting the same line over and over again? I would greatly appreciate the help! Been stumbled on this for a while :(

This is my file to be read:

Sample
Text With
Multiple
Lines
}

My output console shows this:

Sample
Text With
Multiple
Lines
}

But my file that it was writing to shows only the last line which is:

}

EDIT: This is the solution

let writeFileHandle = NSFileHandle(forWritingAtPath: myWriteFile) // Declare the write file handler
while var lineRead = readFileObj?.nextLine() { // Read line by line from the template
        lineRead += "\n"
        let data = (lineRead as NSString).dataUsingEncoding(NSUTF8StringEncoding) // Convert the String to NSData object
        writeFileHandle?.writeData(data!) // Write the NSData object to the file
}

Upvotes: 1

Views: 754

Answers (1)

Ken Thomases
Ken Thomases

Reputation: 90531

The method -[NSString writeToFile:atomically:encoding:error:] writes out a file containing the string. The string constitutes the whole contents of the new file. That's what it does.

You need to use a completely different approach. For example, you can create an NSFileHandle using +fileHandleForWritingAtPath: before your loop and then repeatedly write to it using -writeData:. You would need to convert the string to a data object using -[NSString dataUsingEncoding:]. If your strings don't already have newlines, you'll want to append them before converting to data objects.

Upvotes: 2

Related Questions