【WINDOWS核心编程】windows获取路径的方法

【一】GetCurrentDirectory获取当前进程的当前目录(避免使用

DWORD GetCurrentDirectory(

DWORD   nBufferLength,//sizeofdirectorybuffer
LPTSTR   lpBuffer//directorybuffer
);

参数说明
nBufferLength 缓冲区的长度
lpBuffer 指定一个预定义字串,用于装载当前目录
返回值
调用成功 返回装载到lpBuffer的字节数。
使用GetLastError函数可获得错误信息。

【注意】:
这个函数有点怪异,本来确实是可执行文件的所在目录,但是当用文件对话框成功打开一个文件后,该目录就被修改为被打开的文件所在目录。比如在程序中使用"123.txt"这样的文件名,希望将它存储在exe文件所在目录中,但是当用户用文件对话框打开一个文件"F:\456.txt"后,这个123.txt会被存储到F盘下。 

//字符编码集为Unicode

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

wstring MyGetCurrentDirectory()
{
    wstring result;
    DWORD size = GetCurrentDirectory(0, NULL);
    wchar_t *path = new wchar_t[size + 1];
    if (GetCurrentDirectory(size, path) != 0)
    {
        result = path;
        printf("The currentDirectory is %s", result);
    }
    delete[] path;
    return result;
}

int main()
{
    MyGetCurrentDirectory();
    system("pause");
    return 0;
}

 

【二】GetModuleFileName取一个模块(exe,dll)在磁盘上的路径(建议使用)
DWORD GetModuleFileName(
   HMODULE hModule,     // handle to module。将要得到的模块的句柄。如果是当前模块,NULL
   LPTSTR lpFilename,      // path buffer   得到的文件名。
   DWORD nSize              // size of buffer   一般MAX_PATH就可以了
);

【三】GetFullPathName

DWORD WINAPI GetFullPathName(
  _In_   LPCTSTR lpFileName,
  _In_   DWORD nBufferLength,
  _Out_  LPTSTR lpBuffer,
  _Out_  LPTSTR *lpFilePart
);

参数说明:

lpFileName [in]

文件名。

该参数既可以是一个短文件名,也可以是一个长文件名,还可以是共享名或卷名。

nBufferLength [in]

接收路径的缓冲区的长度。

lpBuffer [out]

这是一个输出参数,指向路径缓冲区的指针。

lpFilePart [out]

输出参数,指向路径缓冲区中文件名部分的指针。该参数可以是NULL。如果lpBuffer指向的缓冲区内存放的是一个目录而非文件,lpFilePart为0。

//字符编码集为Unicode

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

void MyGetFullPathName()
{
    const int BUFSIZE = 4096;
    DWORD  retval = 0;
    BOOL   success;
    TCHAR  buffer[BUFSIZE] = TEXT("");
    TCHAR  buf[BUFSIZE] = TEXT("");
    TCHAR** lppPart = { NULL };
    retval = GetFullPathName(L"1.txt", BUFSIZE, buffer, lppPart);
    if (retval == 0)
    {
        // Handle an error condition.
        printf("GetFullPathName failed (%d)\n", GetLastError());
        return;
    }
    else
    {
        _tprintf(TEXT("The full path name is:  %s\n"), buffer);
        if (lppPart != NULL && *lppPart != 0)
        {
            _tprintf(TEXT("The final component in the path name is:  %s\n"), *lppPart);
        }
    }

}

int main()
{
    MyGetFullPathName();
    system("pause");
    return 0;
}

//Output-->The full path name is:  E:\visual studio 2015\Projects\02_CPPLearn\WINDOWSAPI\WINDOWSAPI\1.txt

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值