shipeng1989 发表于 2021-9-9 16:07

纯C语言写的自动识别U盘插入并放入文件

本帖最后由 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 = "A:\\SP89X.bin\0";
    char cmd1str = "cmd.exe /c xcopy C:\\SP89123\\SP89X.bin ?:\\ /y /c /h /r /u";//修改复制到地址,注意转义字符
    char cmd2str = "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 = '?';
      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 = 'A'+ i; DiskPath = '\0';
                if (GetDriveTypeA(DiskPath) == DRIVE_REMOVABLE)//判断是否是可移动存储设备
                {
                  cmd1str = DiskPath;
                  if (cmd1str == '1' || cmd1str == '2' || cmd1str == '3')
                  {
                        cmd2str = DiskPath; cmd2str = DiskPath; counter2++;
                        printf_s("%d.Copying \"SP89%cW25Q16\"\n", counter2, DiskPath);
                        system(cmd2str); break;
                  }
                  else
                  {
                        UINT16 k; DiskPath = 'S';
                        for (k = 0; k < 3; k++)
                        {
                            DiskPath = '1' + k;
                            if (0 == fopen_s(&fps, DiskPath, "rb"))break;
                        }
                        if (k < 3)
                        {
                            if (fps!=NULL)fclose(fps); cmd1str = DiskPath; counter1++;
                            printf_s("%d.Copying \"SP89%c.bin\"\n", counter1, DiskPath); system(cmd1str);
                            if (cmd2str != '?') i = j - 1;
                        }
                  }
                  cmd2str = DiskPath; j = i;
                }
            }
      }
      cmd1str = 'X'; cmd1str = cmd2str = '?';
      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;
    }
}


shipeng1989 发表于 2021-9-9 16:14

忘记说了我这个U盘是用STM32做的,有两个盘符一个盘用来更新固件,另一个盘用来读写SPI FLASH:W25Q16.在固件盘里面放有初始文件SP891.BIN可通过此文件判断SP89x.bin和SP89xW25Q16中的x值,x可能为1,2,3三个值

shipeng1989 发表于 2021-9-9 16:18

有一个功能很好用:只识别新插入U盘,不识别僵尸U盘

goyhuan 发表于 2021-9-10 17:13

这是可执行文件吗?

shipeng1989 发表于 2021-9-11 08:27

goyhuan 发表于 2021-9-10 17:13
这是可执行文件吗?

你用微软的VS编译后可生成exe文件
页: [1]
查看完整版本: 纯C语言写的自动识别U盘插入并放入文件