Download Reference Manual
The Developer's Library for D
About Wiki Forums Source Search Contact

directly modifying a line in a file

Moderators: larsivi kris

Posted: 02/21/09 16:10:34

Is there a function in Tango to jump to a specific line in a text file and modify it? I mean I can go through the text file with the LineIterator? but afaik I can't directly modify it.

Author Message

Posted: 02/22/09 05:47:04

no, not specifically, since there's usually some adjustment required in order to move the rest of the file content. You could always write each line out to a new file, replace or remove the line of interest, and then write out any remaining lines

Posted: 02/22/09 06:00:11 -- Modified: 02/22/09 16:17:11 by
IceFex

edit: here it is

void ModifyLine(char[] fileName, int lineNumber, char[] string, char[] lineDelimiter = "\n")
{
	auto file = new File (fileName);
	auto lines = splitLines (cast(char[]) file.read);
	file.write("");
	
	lines[lineNumber-1] = string;

	foreach (line; lines)
	{
		file.append(cast(char[])line ~ lineDelimiter);		
	}
}