函数GetFullPathName的细节
一开始查看了在线的msdn,看到这样的示例:
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#define BUFSIZE 4096
#define LONG_DIR_NAME TEXT("c:\\longdirectoryname")
void _tmain(int argc, TCHAR *argv[])
{
DWORD retval=0;
BOOL success;
TCHAR buffer[BUFSIZE]=TEXT("");
TCHAR buf[BUFSIZE]=TEXT("");
TCHAR** lppPart={NULL};
if( argc != 2 )
{
_tprintf(TEXT("Usage: %s [file]\n"), argv[0]);
return;
}
// Retrieve the full path name for a file.
// The file does not need to exist.
retval = GetFullPathName(argv[1],
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);
}
}
在vs2010下执行结果不正确,lppPart总是为0。后来在网上搜索一番,发现是调用函数时传递的最后一个参数不对。
函数定义如下:
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。
问题就出在最后一个参数lpFilePart的定义上。微软定义为:
TCHAR** lppPart={NULL};但实际改为TCHAR* lppPart={NULL};即可,当然,后面的代码也要作出相应的变动,具体见下面修改后的代码。
#include<iostream>
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
using namespace std;
#define BUFSIZE 4096
#define LONG_DIR_NAME TEXT("c:\\longdirectoryname")
void _tmain(int argc, TCHAR *argv[])
{
DWORD retval=0;
BOOL success;
TCHAR buffer[BUFSIZE]=TEXT("");
TCHAR buf[BUFSIZE]=TEXT("");
TCHAR* lppPart={NULL};
// Retrieve the full path name for a file.
// The file does not need to exist.
retval = GetFullPathName(L"C:\\Users\\yeosn\\Desktop\\b.dwg",
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);
wcout<<lppPart<<endl;
}
}
总结:
这个问题主要出在二级指针的运用上。TCHAR** lppPart={NULL};的写法虽然定义了一个二级指针,也进行了初始化,但并没有对一级指针初始化,所以在后面的代码中调用*lppPart会失败。