本帖最后由 shipeng1989 于 2021-9-9 16:22 编辑
最近有个需求:当插入U盘后自动放入指定文件。功能是很简单的但是无奈我只会单片机编程不懂上位机编程,写起来也算是废了不少周折不过最终还是写出来了并且达到了预期的效果。下面我把源代码分享出来方便大家量体裁衣各取所需:(用微软VC编译)
#include <stdio.h>
#include <stdlib.h>
#include <io.h>
#include <string.h>
#include <windows.h>
int main(void)
{
FILE* fps = 0;
UINT32 counter1 = 0,counter2 = 0;
DWORD gld_res1 = 0, gld_res2 = 0;
char DiskPath[MAX_PATH] = "A:\\SP89X.bin\0";
char cmd1str[200] = "cmd.exe /c xcopy C:\\SP89123\\SP89X.bin ?:\\ /y /c /h /r /u";//修改复制到地址,注意转义字符
char cmd2str[200] = "cmd.exe /c xcopy C:\\SP89123\\SP89XW25Q16\\*.* ?:\\ /e /q /h /d";
while (1)
{
do { Sleep(100); gld_res1 = GetLogicalDrives(); }
while (gld_res1 == gld_res2); printf_s("\n"); cmd2str[33+11] = '?';
for (UINT16 i=0,j=0; i < 26 && (gld_res1>>i)!=0; i++)
{
if ((gld_res1 & (1 << i)) != 0 && (gld_res2 & (1 << i)) == 0)
{
DiskPath[0] = 'A'+ i; DiskPath[3] = '\0';
if (GetDriveTypeA(DiskPath) == DRIVE_REMOVABLE)//判断是否是可移动存储设备
{
cmd1str[27 + 11] = DiskPath[0];
if (cmd1str[21 + 11] == '1' || cmd1str[21 + 11] == '2' || cmd1str[21 + 11] == '3')
{
cmd2str[21+11] = DiskPath[7]; cmd2str[33+11] = DiskPath[0]; counter2++;
printf_s("%d.Copying \"SP89%cW25Q16\"\n", counter2, DiskPath[7]);
system(cmd2str); break;
}
else
{
UINT16 k; DiskPath[3] = 'S';
for (k = 0; k < 3; k++)
{
DiskPath[7] = '1' + k;
if (0 == fopen_s(&fps, DiskPath, "rb"))break;
}
if (k < 3)
{
if (fps!=NULL)fclose(fps); cmd1str[21 + 11] = DiskPath[7]; counter1++;
printf_s("%d.Copying \"SP89%c.bin\"\n", counter1, DiskPath[7]); system(cmd1str);
if (cmd2str[33+11] != '?') i = j - 1;
}
}
cmd2str[33+11] = DiskPath[0]; j = i;
}
}
}
cmd1str[21 + 11] = 'X'; cmd1str[27 + 11] = cmd2str[33+11] = '?';
if (gld_res1 > gld_res2)
{
printf_s("Total Copied \"SP89x.bin\" : %d.\n", counter1);
printf_s("Total Copied \"SP89xW25Q16\" : %d.\n", counter2);
printf_s("USB PORT DETECTING...");
}
else printf_s("=========================================================");
gld_res2 = gld_res1;
}
}
|