huidong

首页 | 会员登录 | 关于争取 2022 寒假做出汇东网 Ver3.0.0 !
搜索文章


先说一句

得到程序目录,有一种方法更加保险,因为文件选择器有可能会更改程序的工作目录,使其得到的路径不是真实路径(原因见:http://huidong.xyz/index.php?mode=2&id=173 ),所以可以参考:http://www.huidong.xyz/index.php?mode=2&id=214 的方法。这个方法可以确保你得到的目录确确实实是程序的真实目录



程序全路径(比如 "D:\myapp\test.exe")

wchar_t strProgramFile[1024];
GetModuleFileName(NULL, strProgramFile, 1024); //调用win api 获得程序全路径

函数得到的路径字符串类型是char还是wchar_t取决于项目字符集



目录路径(不含xxx.exe,比如 "D:\myapp")

使用_getcwd函数,可以得到程序的文件目录(不含xxx.exe),需要包含此头文件:

#include <direct.h>

不同的编译器需要的头文件不一样,上面那个是VS需要的,其它的可以查百科

使用示例:

    // 得到char型路径
    char path[1024] = { 0 };
    _getcwd(path, 1024);


如果要wchar_t类型的路径,无需转换字符串类型,直接使用 _wgetcwd 函数 即可。



程序文件名(比如 "test.exe")

首先获取全路径的字符串,再从中得到它的文件名。

请使用http://huidong.xyz/index.php?mode=2&id=205 中的GetFileName函数得到全路径对应的文件名。


GetFileName函数

char *GetFileName(char *p) //得到一个路径的纯文件名
{
    int x = strlen(p);
    char ch = '\\';
    char *q = strrchr(p,ch);
    return q + 1;
}


比如:

#include <windows.h>
#include <stdio.h>

char *GetFileName(char *p) //得到一个路径的纯文件名
{
    int x = strlen(p);
    char ch = '\\';
    char *q = strrchr(p,ch);
    return q + 1;
}

int main()
{
    char* strProgramFile = new char[1024];
    GetModuleFileName(NULL, strProgramFile, 1024); //调用win api 获得程序全路径
    strProgramFile = GetFileName(strProgramFile);
    printf(strProgramFile);
    while(1);
    return 0;
}


示例代码中的输出即是程序文件名。



返回首页


Copyright (C) 2018-2024 huidong