Find a file along the Windows PATH variable

Average rating
(0 votes)

This snippet uses the Windows OS to find a file in any of the directories currently set in the PATH variable. Useful if you want to locate executable files (e.g. "latex.exe") that are normally registered in the PATH. There are more general ways to achieve this in Igor for a file stored anywhere on drives accessible to you, but they're much slower...

Tested with IP6.12 on a WinXP machine.

function/S FindFileAlongWindowsPath(fileNameAndExt)
string fileNameAndExt
 
	string tmpDir = SpecialDirPath("Temporary", 0, 1, 0), tmpFile = "FindFileAlongWindowsPath.txt"
	string tmpFileWinPath = "\"" + ReplaceString("\\",tmpDir, "\\\\") + tmpFile + "\""	// double "\" escaping imposed by Igor
	string cmdPattern = "cmd /c \"%s\"", cmd, result
	variable refnum
 
	// 1. Let Windows find the file in the paths present in the PATH variable 
	// We use a trick by employing the "enhanced substitution of FOR variable references" feature.
	// Documentation of the "FOR /F" command can be found, e.g., at <http://www.pc-ask.com/xp-dos/xp-dos-cmd.html>.
	// The argument to "@echo" has a leading "." to avoid getting gibberish in case the file is not found.
	sprintf cmd, cmdPattern, "for /f %Z in (\"" + fileNameAndExt + "\") do @echo .%~$path:Z > " + tmpFileWinPath
	ExecuteScriptText/B cmd
 
	// 2. Read back the result
	Open refnum as tmpDir+tmpFile	// since "Igor currently cannot read from a console application's standard output"
	FReadLine refnum, result			// we wrote the result to a temprorary file and read that in here
	Close refnum
 
	// 3. Clean up temporary file
	sprintf cmd, cmdPattern, "del " + tmpFileWinPath
	ExecuteScriptText/B cmd
 
	return result[1,strlen(result)-3]	// remove leading "." and trailing " \n"; returns empty string if file not found.
end

Back to top