来源 :http://blog.csdn.net/gukesdo/article/details/6866741
c++ 获取当前路径
[cpp] view plaincopy
    #include <iostream>  
    #include <windows.h>  
    #include <string>  
    using namespace std;  
    int main()  
    {  
        char buf[1000];  
        int i=1000;  
        GetCurrentDirectory(1000,buf);  //得到当前工作路径  
        cout<<buf<<endl;  
      
        string a;  
        a.assign(buf);  
        cout<<a<<endl;  
        //这里加入的路径必须是正确的路径,如果加入
错误的路径,如大小写  
        //和目录名不一样,还有空格,名字不相同等,都会导致SetCurentDirectory  
        //设置路径不成功,从而导致GetCurrentDirectory获取不到正确的路径,这样  
        //GetCurrentDirectory获取的路径就是当前路径或者是上一次SetCurrentDirectory  
        //设置成功的那个路径,GetCurrentDirectory获取一般是不会出错的。  
          
        /**在这里添加路径的时候,每一次都用到两个\,这样做的原因是为了防止文件 
        的目录名中出现
转义字符,比如如果目录名字是以t开头的,则\t
意义 
        就是制表符,而不是目录名。并且惊奇的
发现,在这里使用两个/可以达到相同 
        的效果,不知道是什么原因,很可能是因为在操作系统内部就是这样做的,因为 
        在cmd 
dos命令行下,路径都是以/分割的,而在文件目录名显示的时候则是以\分 
        割的,而且在dos命令行下切换目录的时候这两种也都可以!甚至是两者混写都可以. 
        为了规范都写成\\***/  
      
        //设置为当前工作路径为当时的上一级  
        //a.append("//..//");  
        //a=a+"..//";  
        a.append("\\..\\");  
        //随意设置路径,只要是正确的,否则会导致SetCurrentDirectory执行错误  
        //a.append("//..//..//
Service_Windows//Servic_Windows");  
        //a.append("\\..\\Service_Windows\\Service_Windows");  
        a.append("\\..\\Service_Windows//Service_Windows");  
      
        int test = SetCurrentDirectory(a.c_str());  //设置当前路径值  
        if (test == 0 )  
        {  
            cout << "execute 
failed\n";  
        }  
        GetCurrentDirectory(1000,buf);  
        //这里用两个反斜杠是必须得,因为这不通过操作系统来进行目录切换,  
        //只是简单的字符串拼接  
        strcat(buf,"\\Srvice_Windows\\Srvice_Windows");  
        cout << buf << endl;  
          
        a.assign(buf);  
        test = SetCurrentDirectory(a.c_str());  
        if (test == 0 )  
        {  
            cout << "execute failed\n";  
        }  
        GetCurrentDirectory(1000,buf);  
        cout<<buf<<endl;  
      
        return 0;  
    }  
附件test.cpp 为开发windows服务代码。
  
  
  
    
      
        
          - Downloads.7z (1.4 KB)
- 下载次数: 1