Announcements

Between mid-October and November, the content on AREA will be relocated to the Autodesk Community M&E Hub and the Autodesk Community Gallery. Learn more HERE.

Mel how to remove the carriage return at the end of my text file.

Mel how to remove the carriage return at the end of my text file.

malcolm_341
Collaborator Collaborator
686 Views
1 Reply
Message 1 of 2

Mel how to remove the carriage return at the end of my text file.

malcolm_341
Collaborator
Collaborator

Hello, I'm trying to remove an additional carriage return at the end of an external text file, is there a way to do this in Mel?

0 Likes
Accepted solutions (1)
687 Views
1 Reply
Reply (1)
Message 2 of 2

malcolm_341
Collaborator
Collaborator
Accepted solution

So this was quite challenging, I ended up with a workaround. Instead of removing the carriage return at the end of the text file I always add a carriage return to the end, this way when I use the append command to add text to the file it always has a consistent file to begin with so I can remove my "\n" from my text write proc and keep the file from growing each time the proc is executed. I feel like there's a better way to do this without opening and closing the file so many times, but I couldn't figure it out. Probably won't make sense, but here's the code to prep the file before writing into it.

//Find Maya current version script folder
string $mayaScriptDir = `internalVar -userScriptDir`;
	
//Create file path
string $filePath = ($mayaScriptDir + "userSetup.mel");
	
//See if userSetup.mel exists
int $userSetupExists = `file -q -exists $filePath`;
	
//Define file id
int $fileId;
	
//Create file if it doesn't exist and write text into it
if ($userSetupExists == 0)
{
	//Open file
	$fileId = `fopen ($mayaScriptDir + "userSetup.mel") "a"`;
	//Write text into file
	fprint $fileId ("\n" + $m341_extraHUD_print_textArray[0]);
	//Close file
	fclose $fileId;
}

//If file exists
if ($userSetupExists == 1)
{
	//Strip white space and add carriage return to append works correctly
	//Open file
	$fileId = `fopen $filePath "r"`;
	
	//Get The First Line
	string $nextLine = `fgetline $fileId`;
	
	//Define string array
	string $dataArray[];
	$dataArray = {""};
		
	while (size($nextLine) > 0)
	{
		//Strip whitespace from the beginning and end of line
		string $cleanLine = strip($nextLine);
		
		//Add to array
		$dataArray[size($dataArray)] = $cleanLine;
		
		//Get next line and continue
		$nextLine = `fgetline $fileId`;
	}

	//Remove first line from array to fix line counting
	stringArrayRemoveAtIndex(0,$dataArray);
	fclose $fileId;
		
	//Add carriage return to end of file so append works consistently
	//Open file
	$fileId = `fopen $filePath "w"`;
		
	//Print array to file
	int $counter = 0;
	for ($item in $dataArray)
	{
		fprint $fileId ($dataArray[$counter] + "\n");
		$counter = $counter + 1;
	}
	//Close File
	fclose $fileId;
}

 

0 Likes