第一步:要获取当前windows用户的桌面路径,我们可以使用SHGetFolderPath
函数
TCHAR desktopPath[MAX_PATH];
SHGetFolderPath(NULL, CSIDL_DESKTOPDIRECTORY, NULL, 0, desktopPath)
第二步:获取当前用户桌面下特定类型的文件,使用findfirst、findnext、findclose
函数,来查找文件;sscanf
函数来截取想要的字符串,strcat_s
来拼接字符串。
TCHAR ExtName[MAX_PATH] = "\\*.lnk"; //定义需要查找的文件类型
strcat_s(desktopPath, sizeof(desktopPath), ExtName); //拼接目录和文件后缀名
char* to_search = desktopPath;
intptr_t handle; //用于查找的句柄 intptr_t(long long)
//long long handle
struct _finddata_t fileinfo; //文件信息的结构体
handle = _findfirst(to_search, &fileinfo); //第一次查找
if (-1 == handle)
return -1; //句柄返回值为-1,表示查找失败,返回0 表示查找成功;
//循环查找其他符合的文件,知道找不到其他的为止
do
{
char FullPath[MAX_PATH]; //定义FullPath用于接受完整文件路径
sscanf(desktopPath, "%[^*]", FullPath); //截取一部分我想要的字符串
strcat_s(FullPath, sizeof(FullPath), fileinfo.name); //拼接目录和字符串
printf("%s\n", FullPath);
} while (_findnext(handle, &fileinfo) == 0);
_findclose(handle); //关闭句柄
第三步:我们获取当前程序所在的绝对路径,使用getcwd
函数
//获取当前当前程序所在的绝对路径
char curpath[MAX_PATH];
getcwd(curpath, sizeof(curpath));
strcat_s(curpath, sizeof(curpath),"\\", fileinfo.name);
strcat_s(curpath, sizeof(curpath), fileinfo.name);
第四步:将文件复制到当前程序所在目录下,使用copyfile函数。
CopyFile(FullPath,curpath, FALSE);
第五步:我们将上述函数组合起来使用。同时要保持生成的可执行程序静默运行。
#pragma comment( linker, "/subsystem:windows /entry:mainCRTStartup" ) //保持exe程序静默运行
#define _CRT_SECURE_NO_WARNINGS //可以帮助我使用一些被定义为不安全的函数
#include <stdio.h>
#include <windows.h>
#include <shlobj.h>
#include <string.h>
#include <io.h>
int GetUserPath()
{
TCHAR desktopPath[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_DESKTOPDIRECTORY, NULL, 0, desktopPath))) {
//printf("Current User Path:%ls\n", desktopPath);
TCHAR ExtName[MAX_PATH] = "\\*.lnk"; //定义需要查找的文件类型
strcat_s(desktopPath, sizeof(desktopPath), ExtName); //拼接目录和文件后缀名
char* to_search = desktopPath;
intptr_t handle; //用于查找的句柄 intptr_t(long long) 也就是long long handle
struct _finddata_t fileinfo; //文件信息的结构体
handle = _findfirst(to_search, &fileinfo); //第一次查找
if (-1 == handle)
return -1; //句柄返回值为-1,表示查找失败,返回0 表示查找成功;
//printf("%s\n", fileinfo.name); 打印出找到的文件的文件名
//循环查找其他符合的文件,知道找不到其他的为止
do
{
char FullPath[MAX_PATH]; //声明一个变量FullPath用于接受完整文件路径
sscanf(desktopPath, "%[^*]", FullPath); //截取*之前的字符串赋值到FullPath中
strcat_s(FullPath, sizeof(FullPath), fileinfo.name); //拼接字符串和文件名
//获取当前当前程序所在的绝对路径
char curpath[MAX_PATH];
getcwd(curpath, sizeof(curpath));
strcat_s(curpath, sizeof(curpath),"\\", fileinfo.name);
strcat_s(curpath, sizeof(curpath), fileinfo.name);
//将文件复制到当前程序所在目录下
CopyFile(FullPath,curpath, FALSE);
} while (_findnext(handle, &fileinfo) == 0);
_findclose(handle); //关闭句柄
}
else {
printf("get path failed!");
}
}
int main() {
GetUserPath();
return 0;
}
测试环境:windows11+ visual studio 2022