Mel: Reading/Writing a text file

From wikinotes

Opening a File:

string $filePath = C:/test.txt;				//sets filePath to a variable

int $fileID = fopen($filePath, "r");			//opens file + sets whether to read "r", write "w", or read/write "+"



Reading from a File:

Get all information from a file: (fread)

string $allLines = `fread $fileID $allLines`;				//$allLines becomes a block of all text in the file



Get all information, line by line: (fgetline)

string $nextLine = `fgetline $fileID`;

while (size($nextLine) > 0) {
	print $nextLine;
	$nextLine = `fgetline $fileID`;
}



clear Whitespace (spaces before+after all text) line by line: (strip)

string $nextLine = `fgetline $fileID`;

while (size($nextline) > 0) {
	string $cleanline = strip($nextline);
	print $cleanline;
	$nextLine = `fgetline $fileID`;
}



Read a File, word by word (fgetword, !feof)

while(!feof($fileID){
	print ($nextWord + "\n";
	$nextWord = `fgetword($fileID);
}
**Note**
!feof will search until the end of a word file, but it does not end loop if the file is empty.



Writing to a File:

string $myStrArray[] = {"This is line 1", "This is line 2", "Line 3"};

string $filePath = "C:/test2.txt";						//sets the path to the file


$fileID = `fopen $filePath "a";							//"a" appends, "w" replaces the entire file



for ($line in $myStrArray)							//writes a line to $fileID with a new line for
	fprint $fileID ($line + "\n");						//each array entry


fclose $fileID;									//this closes your opened file.
										//this is essential to:
										//	a) save your file
										//	b) prevent maya from crashing.