c++_获取程序运行的目录

#include <iostream>
#include <direct.h>  
#include <stdio.h> 
#include <Windows.h>

//Unicode字符集    获取exe/dll所在路径下的目录
std::string GetProgramDir()
{
    wchar_t exeFullPath[MAX_PATH]; // Full path 
    std::string strPath = "";

    GetModuleFileName(NULL, exeFullPath, MAX_PATH);
    char CharString[MAX_PATH];
    size_t convertedChars = 0;
    wcstombs_s(&convertedChars, CharString, MAX_PATH, exeFullPath, _TRUNCATE);

    strPath = (std::string)CharString;    // 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 
}

//多字节环境下    获取exe所在的路径
//std::string GetProgramDir2()
//{
//    char exeFullPath[MAX_PATH]; // Full path 
//    std::string strPath = "";
//
//    GetModuleFileName(NULL, exeFullPath, MAX_PATH);
//    strPath = (std::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()
{
	//获取当前的工作目录
	char   buffer[MAX_PATH];
	_getcwd(buffer, MAX_PATH);
	std::cout << buffer << std::endl;

    //获取当前的工作目录
    wchar_t pBuf[MAX_PATH];             
    GetCurrentDirectory(MAX_PATH, pBuf);    
    std::wcout << pBuf << std::endl;

    //获取exe或dll所在的路径
    wchar_t defaultPath[MAX_PATH];
    GetModuleFileName(NULL, defaultPath, MAX_PATH);
    std::wcout << defaultPath << std::endl;

    std::string str = GetProgramDir();
    std::cout << str << std::endl;

	system("pause");
	return 0;
}

参考博客: 

C++中获取当前运行路径_c++ 获取当前路径_聂炳玉的博客-CSDN博客

C++ 获取当前程序路径_c++获取当前程序的路径_哭哭啼的博客-CSDN博客

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值