分清程序“所在路径”和“执行路径”
我的一个程序在执行时需要调用其所在路径下的数据文件。这个程序在独立运行时没有问题,但用第三方程序将其作为子进程加载后,却发生了无法找到数据文件的错误。其原因:我是通过相对路径查找数据文件的,在由第三方程序调用该程序时,执行路径是第三方程序所在路径,所以无法通过原相对路径找到数据文件。因此,我们有必要明确程序的“所在路径”和“执行路径”,才能正确地处理相对路径文件引用。
下面给出C、C#和Python中,获取程序“所在路径”和“执行路径”的方法。其中的C程序只在Windows下有效,在Linux下缺乏现成的函数,需要“曲线”现实,可参见coldcrane的专栏中《Linux下GetModuleFileName的四种写法》一文。
- #include <stdio.h>
- #include <windows.h>
- #define MAXPATH 256
- int main()
- {
- char str[MAXPATH];
- GetModuleFileName(NULL, str, MAXPATH);
- *(strrchr(str, '\\')) = '\0';
- printf("The program is in: %s\n", str);
- getcwd(str, MAXPATH);
- printf("The program runs at: %s\n", str);
- return 0;
- }
- using System;
- namespace CSharp
- {
- class Program
- {
- static void Main(string[] args)
- {
- string str;
- str = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
- str = str.Substring(0, str.LastIndexOf("\\"));
- Console.WriteLine("The program is in: " + str);
- str = System.IO.Directory.GetCurrentDirectory();
- Console.WriteLine("The program runs at: " + str);
- }
- }
- }
- #!/usr/bin/python
- import os
- if __name__ == '__main__':
- print "The program is in: %s" % os.path.dirname(__file__)
- print "The program runs at: %s" % os.getcwd()
附:Windows下简单测试的方法。在以上代码末尾添加诸如getchar()一类的暂停效果指令,编译之(当然Python就不用了),对生成的可执行文件建立快捷方式,修改快捷方式的属性,将“Start in(起始位置)”设为有别于程序所在路径的其它位置。运行这个快捷方式,观察“The program is in:”与“The program runs at:”的不同。




