gpt4 book ai didi

c++ - 在缓冲区内分离数据时出现问题 (WinAPI)

转载 作者:行者123 更新时间:2023-11-30 16:48:56 26 4
gpt4 key购买 nike

我在网上找到了这段代码,它 promise 将加载到缓冲区的数据分开,我需要它,这样我就可以在屏幕上单独显示每个 .bmp 图像。

BOOL OpenBmpFile(char* filePath, char* fileName, int* offset, HWND hwnd)
{
OPENFILENAME ofn;
char szFileName[256];
char szFilePath[256];
BOOL FileOK;

memset(&ofn, 0, sizeof(ofn));
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hwndOwner = hwnd;
ofn.lpstrFilter = TEXT("Bitmap Files (*.bmp)\0*.bmp\0\0");
ofn.nFilterIndex = 1;
strcpy(szFilePath, "*.bmp");
ofn.lpstrFile = (LPWSTR)szFilePath;
//
// Set lpstrFile[0] to '\0' so that GetOpenFileName does not
// use the contents of szFile to initialize itself.
//
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFilePath);
ofn.lpstrFileTitle = (LPWSTR)szFileName;
ofn.nMaxFileTitle = sizeof(szFileName);
ofn.lpstrTitle = TEXT("Open BMP File");
ofn.Flags = OFN_SHOWHELP | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_LONGNAMES | OFN_ALLOWMULTISELECT | OFN_EXPLORER;


// show the common dialog "Open BMP File"
FileOK = GetOpenFileName(&ofn);

// if cancel, exit
if (!FileOK)
return FALSE;

// else store the selected filename
strcpy(fileName, szFileName);
//I use this because strcpy stops after the first NULL
memcpy(filePath, szFilePath, sizeof(szFilePath));
*offset = ofn.nFileOffset;

if(szFilePath[ofn.nFileOffset-1] != '\0')
{
MessageBox(hwnd,L"Single Selection",L"Open Debug 1",MB_OK);
}
else
{
MessageBox(hwnd,L"Multiple Selection",L"Open Debug 2",MB_OK);
}

return TRUE;
}

但是,每次我使用以下行调用此函数都会导致错误:

OpenBmpFile((char*)file, (char*)file2, pTest, hWnd);

错误:pTest 是 nullptr;

我想我的问题是,如何有效地使用此功能来显示我的图像?

最佳答案

您所犯的最大错误是将 ANSI 和 Unicode 混合在一起。您正在使用 char[] 缓冲区并将其类型转换为 LPWSTR 指针,以便将它们分配给 OPENFILENAME 字段。由于您使用的是 API 的 TCHAR 版本,这意味着您的项目正在针对 Unicode 而不是针对 ANSI 进行编译。因此,API 需要 Unicode 缓冲区,并将输出 Unicode 字符串。这也意味着您告诉 API 您的缓冲区分配的空间有两次可用于接收字符,因为您正在设置 ofn.nMaxFileofn.nMaxFileTitle 字段转换为字节 计数,而不是字符 计数。所以可能会导致缓冲区溢出。

您不能仅仅将 8 位缓冲区类型转换为 16 位数据类型。您必须首先为缓冲区使用正确的数据类型,并消除类型转换。在这种情况下,这意味着使用 WCHAR/wchar_t(或至少 TCHAR)缓冲区而不是 char 缓冲区。但是,由于您在函数参数中使用 char,因此您应该使用 API 的 ANSI 版本,而不是 TCHAR/Unicode 版本。

当选择多个文件时,尤其是具有长文件名的文件时,生成的字符数据很容易超出固定长度缓冲区的大小。作为OPENFILENAME documentation状态:

lpstrFile
Type: LPTSTR

The file name used to initialize the File Name edit control. The first character of this buffer must be NULL if initialization is not necessary. When the GetOpenFileName or GetSaveFileName function returns successfully, this buffer contains the drive designator, path, file name, and extension of the selected file.

If the OFN_ALLOWMULTISELECT flag is set and the user selects multiple files, the buffer contains the current directory followed by the file names of the selected files. For Explorer-style dialog boxes, the directory and file name strings are NULL separated, with an extra NULL character after the last file name. For old-style dialog boxes, the strings are space separated and the function uses short file names for file names with spaces. You can use the FindFirstFile function to convert between long and short file names. If the user selects only one file, the lpstrFile string does not have a separator between the path and file name.

If the buffer is too small, the function returns FALSE and the CommDlgExtendedError function returns FNERR_BUFFERTOOSMALL. In this case, the first two bytes of the lpstrFile buffer contain the required size, in bytes or characters.

nMaxFile
Type: DWORD

The size, in characters, of the buffer pointed to by lpstrFile. The buffer must be large enough to store the path and file name string or strings, including the terminating NULL character. The GetOpenFileName and GetSaveFileName functions return FALSE if the buffer is too small to contain the file information. The buffer should be at least 256 characters long.

你没有考虑到这一点。 256(最好使用 260,又名 MAX_PATH)适合选择单个文件,但可能不适用于选择多个文件。如果 GetOpenFileName()FNERR_BUFFERTOOSMALL 失败,您将必须重新分配缓冲区并再次调用 GetOpenFileName()

话虽如此,尝试更多类似这样的事情:

BOOL OpenBmpFiles(char **filePath, char** fileNames, HWND hwnd)
{
*filePath = NULL;
*fileNames = NULL;

size_t iMaxFileSize = MAX_PATH;
char *lpFileBuffer = (char*) malloc(iMaxFileSize);
if (!lpFileBuffer)
return FALSE;

char szFileTitle[MAX_PATH];
BOOL bResult = FALSE;

OPENFILENAMEA ofn;
memset(&ofn, 0, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwnd;
ofn.lpstrFilter = "Bitmap Files (*.bmp)\0*.bmp\0\0";
ofn.nFilterIndex = 1;
ofn.lpstrFile = lpFileBuffer;
ofn.nMaxFile = iMaxFileSize;
ofn.lpstrFileTitle = szFileTitle;
ofn.nMaxFileTitle = MAX_PATH;
ofn.lpstrTitle = "Open BMP File";
ofn.Flags = OFN_SHOWHELP | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_LONGNAMES | OFN_ALLOWMULTISELECT | OFN_EXPLORER;

do
{
//
// Set lpstrFile[0] to '\0' so that GetOpenFileName does not
// use the contents of lpstrFile to initialize itself.
//
ofn.lpstrFile[0] = '\0';

// show the common dialog "Open BMP File"
if (GetOpenFileNameA(&ofn))
break;

// if cancel, exit
if (CommDlgExtendedError() != FNERR_BUFFERTOOSMALL)
goto cleanup;

// reallocate the buffer and try again
iMaxFileSize = * (WORD*) lpFileBuffer;
char *lpNewFileBuffer = (char*) realloc(lpFileBuffer, iMaxFileSize);
if (!lpNewFileBuffer)
goto cleanup;

lpFileBuffer = lpNewFileBuffer;

ofn.lpstrFile = lpFileBuffer;
ofn.nMaxFile = iMaxFileSize;
}
while (true);

if (lpFileBuffer[ofn.nFileOffset-1] != '\0')
{
MessageBox(hwnd, TEXT("Single Selection"), TEXT("Open Debug 1"), MB_OK);

// copy the single filename and make sure it is double-null terminated

size_t len = strlen(&lpFileBuffer[ofn.nFileOffset]) + 2;

*fileNames = (char*) malloc(len);
if (!*fileNames)
goto cleanup;

strncpy(*fileNames, &lpFileBuffer[ofn.nFileOffset], len);

// copy the directory path and make sure it is null terminated

lpFileBuffer[ofn.nFileOffset] = '\0';

*filePath = strdup(lpFileBuffer);
if (!*filePath)
{
free(*fileNames);
*fileNames = NULL;
goto cleanup;
}
}
else
{
MessageBox(hwnd, TEXT("Multiple Selection"), TEXT("Open Debug 2"), MB_OK);

// copy the directory path, it is already null terminated

*filePath = strdup(lpFileBuffer);
if (!*filePath)
goto cleanup;

// copy the multiple filenames, they are already double-null terminated

size_t len = (ofn.nMaxFile - ofn.nFileOffset);

*fileNames = (char*) malloc(len);
if (!*fileNames)
{
free(*filePath);
*filePath = NULL;
goto cleanup;
}

// have to use memcpy() since the filenames are null-separated
memcpy(*fileNames, &lpFileBuffer[ofn.nFileOffset], len);
}

bResult = TRUE;

cleanup:
free(lpFileBuffer);
return bResult;
}

然后你可以像这样使用它:

char *path, *filenames;
if (OpenBmpFiles(&path, &filenames, hwnd))
{
char *filename = filenames;
do
{
// use path + filename as needed...
/*
char *fullpath = (char*) malloc(strlen(path)+strlen(filename)+1);
PathCombineA(fullpath, path, filename);
doSomethingWith(fullpath);
free(fullpath);
*/

filename += (strlen(filename) + 1);
}
while (*filename != '\0');

free(path);
free(filenames);
}
<小时/>

更新:或者,为了简化返回文件名的使用,您可以这样做:

BOOL OpenBmpFiles(char** fileNames, HWND hwnd)
{
*fileNames = NULL;

size_t iMaxFileSize = MAX_PATH;
char *lpFileBuffer = (char*) malloc(iMaxFileSize);
if (!lpFileBuffer)
return FALSE;

char szFileTitle[MAX_PATH];
BOOL bResult = FALSE;

OPENFILENAMEA ofn;
memset(&ofn, 0, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwnd;
ofn.lpstrFilter = "Bitmap Files (*.bmp)\0*.bmp\0\0";
ofn.nFilterIndex = 1;
ofn.lpstrFile = lpFileBuffer;
ofn.nMaxFile = iMaxFileSize;
ofn.lpstrFileTitle = szFileTitle;
ofn.nMaxFileTitle = MAX_PATH;
ofn.lpstrTitle = "Open BMP File";
ofn.Flags = OFN_SHOWHELP | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_LONGNAMES | OFN_ALLOWMULTISELECT | OFN_EXPLORER;

do
{
//
// Set lpstrFile[0] to '\0' so that GetOpenFileName does not
// use the contents of lpstrFile to initialize itself.
//
ofn.lpstrFile[0] = '\0';

// show the common dialog "Open BMP File"
if (GetOpenFileNameA(&ofn))
break;

// if cancel, exit
if (CommDlgExtendedError() != FNERR_BUFFERTOOSMALL)
goto cleanup;

// reallocate the buffer and try again
iMaxFileSize = * (WORD*) lpFileBuffer;
char *lpNewFileBuffer = (char*) realloc(lpFileBuffer, iMaxFileSize);
if (!lpNewFileBuffer)
goto cleanup;

lpFileBuffer = lpNewFileBuffer;

ofn.lpstrFile = lpFileBuffer;
ofn.nMaxFile = iMaxFileSize;
}
while (true);

if (lpFileBuffer[ofn.nFileOffset-1] != '\0')
{
MessageBox(hwnd, TEXT("Single Selection"), TEXT("Open Debug 1"), MB_OK);

// copy the single filename and make sure it is double-null terminated

size_t len = strlen(lpFileBuffer) + 2;

*fileNames = (char*) malloc(len);
if (!*fileNames)
goto cleanup;

strncpy(*fileNames, lpFileBuffer, len);
}
else
{
MessageBox(hwnd, TEXT("Multiple Selection"), TEXT("Open Debug 2"), MB_OK);

// calculate the output buffer size

char *path = lpFileBuffer;
size_t pathLen = strlen(path);
bool slashNeeded = ((path[pathLen-1] != '\\') && (path[pathLen-1] != '/'));
size_t len = 1;

char *filename = &lpFileBuffer[ofn.nFileOffset];
while (*filename != '\0')
{
int filenameLen = strlen(filename);
len += (pathLen + filenameLen + 1);
if (slashNeeded) ++len;
filename += (filenameLen + 1);
}

// copy the filenames and make sure they are double-null terminated

*fileNames = (char*) malloc(len);
if (!*fileNames)
goto cleanup;

char *out = *fileNames;

filename = &lpFileBuffer[ofn.nFileOffset];
while (*filename != '\0')
{
strncpy(out, path, pathLen);
out += pathLen;
if (slashNeeded) *out++ = '\\';

int filenameLen = strlen(filename);
strncpy(out, filename, filenameLen);
out += filenameLen;
*out++ = '\0';

filename += (filenameLen + 1);
}

*out = '\0';
}

bResult = TRUE;

cleanup:
free(lpFileBuffer);
return bResult;
}

char *filenames;
if (OpenBmpFiles(&filenames, hwnd))
{
char *filename = filenames;
do
{
// use filename as needed...
/*
doSomethingWith(filename);
*/

filename += (strlen(filename) + 1);
}
while (*filename != '\0');

free(filenames);
}

关于c++ - 在缓冲区内分离数据时出现问题 (WinAPI),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42807802/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com