Author Topic: Write into a file by coding  (Read 927 times)

How would I write into a file by coding? Not create a new file, write into an already existing file. And when I write into it, could I choose a line, and overwrite already existing code?

I DO NOT WANT TO DELETE ALL WITHIN A .CS OR FILE, I WANT TO EDIT. I WILL NOT DO ANYTHING LIKE OX CORP DID.

I made a gui, and I want it so when I press the button it changes some code. could someone make an example of a server comand changing a certian line of code?

Cookies to whoever answers the question correctly!

To add to the end of a file, use %file.openForAppend() instead of openForWrite().

For the other, use a while(!%file.isEOF()) to read the file into an array, replace the given line's place in the array with the one you want, then openForWrite() and write each line.

Create a new text file in the Add-Ons/Client folder called 'Test.txt' and a CS file in the same folder called 'fileReplace.cs'.

Test.txt
Code: [Select]
One
Two
Three
Four
Five
Six
Seven

fileReplace.cs
Code: [Select]
function replace5thHi(%filename)
{
 %file = new FileObject(); //Create file object
 %file.openForRead(%filename); //Open the file. You should add checks for whether file exists etc
 %count = 0; //Setting so it doesn't go %line[""], %line[1], %line[2]
 while(!%file.isEOF())
 {
  %line[%count] = %file.readline();
  %count++;
 }
 %file.close();
 %line[4] = "Hi."; //Replace 5th line with "Hi."
 %file.openForWrite(%filename); //Blank the file and start re-writing lines to it.
 for(%i=0;%i<%count;%i++)
 {
  %file.writeline(%line[%i]);
 }
 %file.close();
 %file.delete();
}

Start the game. Check that no console errors have occurred from it executing the file replace CS file. Open the console:
Code: [Select]
replace5thHi("Add-Ons/Client/Test.txt");
It should report no errors and no echos. Open the test.txt file. If it worked it should be:

Test.txt
Code: [Select]
One
Two
Three
Four
Hi.
Six
Seven

Tell me if it is, I haven't tested it...
« Last Edit: October 15, 2007, 11:19:12 AM by Space Guy »

I do not have time right now, but I hope that works!