我正在尝试获取用户输入并在 CreateProcessW() 函数中使用它。简而言之,用户输入应用程序的路径,程序将其打开。但它正在崩溃。任何帮助。一切都编译得很好。
#include <windows.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <processthreadsapi.h>
#include <errno.h>
void delay(unsigned int mseconds)
{
clock_t goal = mseconds + clock();
while (goal > clock());
}
int main(int argc,char *argv[])
{
LPCWSTR drive[2];
printf("\nEnter the drive, do not include '\\' (Ex. C:) : ");
wscanf(L"%s", drive);
LPCWSTR path = L"\\Windows\\notepad.exe";
STARTUPINFOW siStartupInfo;
PROCESS_INFORMATION piProcessInfo;
memset(&siStartupInfo, 0, sizeof(siStartupInfo));
memset(&piProcessInfo, 0, sizeof(piProcessInfo));
siStartupInfo.cb = sizeof(siStartupInfo);
LPCWSTR pPath;
wprintf(L"%ls%ls\n", drive, path);
printf("\nPlease enter the path exact as shown above: ");
wscanf(L"%s", &pPath);
printf("\nNow opening notepad . . . . \n\n");
delay(3000);
if (CreateProcessW(pPath,
NULL,
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&siStartupInfo,
&piProcessInfo))
{
printf("Notepad opened. . .\n\n");
}
else
{
printf("Error = %ld\n", GetLastError());
}
return 0;
}
顺便说一句,大部分代码都受到了我在网上和此处找到的代码片段的影响。
最佳答案
LPCWSTR drive[2];
您为两个指针分配空间。
printf("\nEnter the drive, do not include '\\' (Ex. C:) : ");
wscanf(L"%s", drive);
哎呀,您正在告诉 wscanf
在您分配的空间中存储字符串。但你只为两个指针分配了空间。
LPCWSTR pPath;
好吧,pPath
是一个尚未指向任何内容的指针。您所拥有的只是一个指针。
wscanf(L"%s", &pPath);
您应该告诉 wscanf
在哪里存储正在输入的字符串。但您从未为字符串分配空间,您只是创建了一个不指向任何内容的指针。
这是我能找到的 wscanf
第一个示例中的一些代码:
wchar_t str [80];
int i;
wprintf (L"Enter your family name: ");
wscanf (L"%ls",str);
注意到它如何为 80 个宽字符的数组分配空间,然后告诉 wscanf
将输入存储在字符数组中吗?
关于c - 我想 C 中的 LPCWSTR 问题,程序崩溃了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59048868/