Script to covert text files (e.g. srt) into UTF-8, without BoM

Here is a button which will do that for the selected files:


EDIT: 31/Aug/2018


Test JScript.dcf (7.0 KB) -- OLD, see edit just above this line.

See: How to use buttons and scripts from this forum.

If it removes the BOM from a file, that file will be deselected. Files that don't start with a UTF-8 BOM will be skipped and left selected.

The script only does minimal error checking, and does not create a backup of the old file before overwriting it, so you might want to create backups first or improve the script if you are going to use it on important data that isn't already backed up.

Click here to see the script code contained in the .dcf above, if you just want to look at how it works without downloading the .dcf:

OLD script code
function OnClick(clickData)
{
	var tab = clickData.func.sourcetab;
	var cmd = clickData.func.command;
	cmd.deselect = false;
	var vecDeselect = DOpus.Create.Vector();
	var blobBOM = DOpus.Create.Blob(0xEF,0xBB,0xBF);
	var blobFile = DOpus.Create.Blob();

	for (var eSel = new Enumerator(clickData.func.sourcetab.selected_files); !eSel.atEnd(); eSel.moveNext())
	{
		var item = eSel.item();
		var file = item.Open("r", tab);

		if (file.error == 0 &&
			file.Read(blobFile, 3) == 3 &&
			file.error == 0 &&
			blobBOM.Compare(blobFile) == 0)
		{
			blobFile.Free();
			file.Read(blobFile);
			if (file.error == 0)
			{
				file.Close();
				file = item.Open("wt", tab);
				if (file.error == 0)
				{
					file.Write(blobFile);
					file.Close();
					vecDeselect.push_back(item);
				}
			}
		}
	}

	if (vecDeselect.size > 0)
	{
		cmd.ClearFiles();
		cmd.AddFiles(vecDeselect);
		cmd.RunCommand("Select DESELECT FROMSCRIPT");
	}
}