Game Development Community

Basic File IO

by Jacob S. · in Torque 3D Professional · 05/18/2010 (1:17 pm) · 2 replies

//-----------------------------------------------------------------
// Code Repository
//-----------------------------------------------------------------
//$file.openforwrite($path @ "test.txt");   
//$file.openForAppend($path @ "test.txt");
//%file.delete();  

%this.path = "";
%this.fileName = "";
%this.file = new fileobject();

//-----------------------------------------------------------------
// Find Location
//-----------------------------------------------------------------

function prewrite() {
   %modpath = findfirstfile("~/main.cs");   
   
   if(isFile(%modpath)) {
      %mymodpath = filePath(%modpath) @ "/";   
   } else {   
      %modpath = findFirstFile("~/main.cs.dso");   
      %mymodpath= filePath(%modpath) @ "/";   
   }
   
   return %mymodpath;  
}

//-----------------------------------------------------------------
// Write Logic
//-----------------------------------------------------------------

function writeToFile(%output) {
   
   if ( $file $= "" ) {
      $file = new fileobject();
      $path = prewrite();
     
     $file.openForAppend($path @ "test.txt");
   }
   
   if ($file.openForAppend($path @ "test.txt")) { 
      $file.writeLine(%output);   
   } else { 
      error("File is not open for writing"); 
   }
}

//-----------------------------------------------------------------
// Read Logic
//-----------------------------------------------------------------

function readFromFile() {
   $path = prewrite();
   
   if ( $file $= "" )
      $file = new fileobject(); 
   
   $file.openForRead($path @ "test.txt");
      
   while(!$file.isEOF()) {   
      echo($file.readLine());    
   }   
   $file.close();     
}

function closeFile() {
   
   $file.close();
}

function TestWrite() {
   
   writeToFile("    -I-    ");
   writeToFile("    -I-    ");
   writeToFile("-Want-");
   writeToFile(" -This- ");
   writeToFile("   -To-   ");
   writeToFile("-Work-");
   closeFile();
}

Edit: I just had a logic error on my part, but the T3D forums(but TGB has many) don't seem to have a thread covering it so I'll fix the code and leave it as an example. Thanks Chris for catching my mistake.

#1
05/18/2010 (6:07 pm)
In the second call to writeToFile() (after $file has been initialised), the local variable %path is used without being initialised.
#2
05/19/2010 (4:22 am)
That's what I get for mixing and matching pre-existing code. lol

Nice catch, I feel a bit embarrased.