如何找到文件的完全限定路径名?
在 Windows 上,您可以转到“运行”,输入“cmd”,按 Enter 键,然后相当轻松地启动“C:\Windows\system32\cmd.exe”。对于“python”或“pythonw”也是如此(尽管第二个示例中没有弹出任何内容)。如果您只知道要执行“python”或“pythonw”并且它位于 PATH 上,那么在 C 中找出可执行文件的完全限定路径名的最简单方法是什么? 这个问题似乎与问题高度相关,但没有给出C中的最终解决方案。 _execp 允许使用字符串“python”或“pythonw”,但需要函数的 argv 参数的第一个参数的限定路径。
On Windows, you can go to "Run," type in "cmd," press enter, and start up "C:\Windows\system32\cmd.exe" rather easily. The same is true for "python" or "pythonw" (though nothing pops up in the second example). If all you know is that you want to execute "python" or "pythonw" and that it is on the PATH, what is the simplest way in C to figure out the fully qualified path name for the executable? This question seems to be highly related to the problem but does not give a final solution in C. _execp allows using the string "python" or "pythonw" but requires the qualified path for the first argument to the argv parameter of the function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 getenv() 获取路径,将其拆分为字符串(Windows 上用分号),然后依次测试每个目录中是否存在指定名称的可执行文件。
将 myfile 替换为任意内容,并在 Windows 上将 ':' 替换为 ';'因为路径分隔符不同。
Use getenv() to get the path, split it into strings (by semicolon on Windows), then test if there is an executable with the specified name in each directory in turn.
Replace myfile with whatever, and on Windows replace ':' with ';' since the path separator is different.
查看 shell API PathResolve (但是,它被标记为“在任何未来的 Windows 版本中都可删除”,所以我会避免使用它)和 PathFindOnPath 相反,它是一个稳定的 API。使用 PathFindOnPath,传递要搜索的文件名(例如 yourexecutable.exe)作为第一个参数,传递 NULL 作为第二个参数。
Have a look at the shell APIs PathResolve (that, however, is marked as "removable in any future windows version", so I'd avoid it) and PathFindOnPath, that, instead, is a stable API. With PathFindOnPath, pass the filename to search (e.g. yourexecutable.exe) as the first parameter and NULL as the second one.
您可以使用 PathFindOnPath(),并通过NULL 表示搜索当前 PATH 环境变量的第二个值。
You can use PathFindOnPath(), and pass NULL for the second value to search the current PATH environment variable.