반응형

linux에서는 realpath 함수,   windows 에서는 GetModuleFileName 함수를 사용하여 실행파일의 절대 경로를 얻습니다. 

 

 

2020. 12. 17 최초작성

2020. 01. 22 윈도우 예제코드 버그 수정. 한글 이름 디렉토리인 경우 문제가 있었음.  



Linux


#include <limits.h> /* PATH_MAX = 4096 */
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char buf[PATH_MAX];
    char *res = realpath(".", buf);
    if (res)
    {
        printf("%s\n", buf);
    } else
    {
        perror("realpath");
        exit(1);
    }

    return 0;
}







Windows


#include <iostream>
#include <Windows.h>
#include <atlconv.h>


int main()
{
wchar_t path[MAX_PATH] = { 0 };
GetModuleFileName(NULL, path, MAX_PATH);

USES_CONVERSION;
std::string str = W2A(path);
str = str.substr(0, str.find_last_of("\\/"));

printf("%s\n", str.c_str());
}



반응형

문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.

도움이 되셨다면 토스아이디로 후원해주세요.
https://toss.me/momo2024


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts