注册 登录
编程论坛 C++教室

GetModuleFileName 获得运行文件路径的问题

smart3503 发布于 2013-01-29 13:37, 740 次点击
#include "Shlwapi.h"
#include <Windows.h>  
#include <iostream>   
#include <string>
using namespace std;   
   
string GetProgramDir()  
{   
    TCHAR exeFullPath[MAX_PATH]; // Full path
    string strPath = "";
    GetModuleFileName(NULL,exeFullPath,MAX_PATH);
    strPath=(string)exeFullPath;    // Get full path of the file,该行运行显示错误,代码见最后
    int pos = strPath.find_last_of('\\', strPath.length());
    return strPath.substr(0, pos);  // Return the directory without the file name
}   
 
int main ()
{
    string str = "";
    str = GetProgramDir();
    cout << str << endl;
    return 0;
}

运行后显示 error C2440: 'type cast' : cannot convert from 'TCHAR [260]' to 'std::string'。不知如何更改,请各路高手支招,多谢!
2 回复
#2
yuccn2013-01-29 13:51
估计你的是用宽字符吧,改成下面的试试。

string GetProgramDir()  
 {   
     char exeFullPath[MAX_PATH]; // Full path
     string strPath = "";
     GetModuleFileNameA(NULL,exeFullPath,MAX_PATH);
     strPath=(string)exeFullPath;   
     int pos = strPath.find_last_of('\\', strPath.length());
     return strPath.substr(0, pos);  // Return the directory without the file name
 }   
#3
smart35032013-01-29 14:27
多谢版主指教,可以了,学的不精,以后多来向版主学习
1