OverwriteLine()

From Hack Wars Wiki

Jump to: navigation, search

This is a function which overwrites the specified line in a given file with the given content.

Code

void overwriteLine(string file, string content, int lineNum)
{
     if(!fileExists(file)) // if the file does not exist, create a new file containing content
     {
          writeLine(file,content);
     }
     else if(lineNum>=countLines(file)) // if lineNum is not in the file, add it to the end of the file
     {
          writeLine(file,content);
     }
     else
     {
          string newcontent = "";
	  int totalLines = countLines(file);
	  for(int i = 0; i < totalLines; i++)
	  {
		if(i==lineNum)
		{
			newcontent += content;
			newcontent += char(10);
		}
		else
		{
			newcontent += readLine(file,i);
			newcontent += char(10);
		}
	  }
	  clearFile(file);
	  writeFile(file,newcontent);
     }
}
TTJ 06:24, 23 November 2008 (UTC)
Personal tools