纯c语言实现的监控windows下U盘的插拔并读取指定文件

#include <windows.h>
#include <dbt.h>
#include <math.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

int readFile(const char * nodeStatus)
{
	FILE *filePtr; // 文件指针
	char filePath[256]; // 存储文件路径的缓冲区
	char line[256]; // 存储每行内容的缓冲区
	const char *directory; // 文件所在的目录路径
	const char *fileName; // 文件名

	directory = nodeStatus;
	fileName = ":\\cfg.ini";

	// 拼接文件路径
	strcpy_s(filePath, sizeof(filePath), directory); // 添加目录路径
	strcat_s(filePath + strlen(directory), sizeof(filePath) - strlen(directory), fileName); // 添加文件名

	// 使用fopen_s函数打开文件
	if (fopen_s(&filePtr, filePath, "r") != 0) { // 以只读模式打开文件
		perror("Error opening file"); // 如果文件打开失败,打印错误信息
		return 1;
	}

	// 使用fgets函数读取文件的每一行
	while (fgets(line, sizeof(line), filePtr) != NULL) {
		printf("%s", line); // 打印每行内容
	}

	// 关闭文件
	fclose(filePtr);

	return 0;
}

LRESULT CALLBACK WndProc(HWND h, UINT msg, WPARAM wp, LPARAM lp)
{
	if (msg == WM_DEVICECHANGE)
	{
		if ((DWORD)wp == DBT_DEVICEARRIVAL)
		{
			DEV_BROADCAST_VOLUME* p = (DEV_BROADCAST_VOLUME*)lp;
			if (p->dbcv_devicetype == DBT_DEVTYP_VOLUME)
			{
				MessageBox(NULL, TEXT("节点已接入"), NULL, NULL);
				//获取盘符,65对应得ASCI码是'A'
				int driveLetter = 65+(int)(log(p->dbcv_unitmask) / log(2));
				//任意盘符根目录下的txt.txt
				
				char filePath[100] = { (char)driveLetter,':','//','t','x','t','.','t','x','t' };

				printf("%s", filePath);
				FILE *filePtr; // 文件指针
				char ch;
				// 打开并读取文件
				if (fopen_s(&filePtr, filePath, "r") != 0) { // 以只读模式打开文件
					perror("Error opening file"); // 如果文件打开失败,打印错误信息
					return 1;
				}
				
				// 读取文件内容
				// 使用fgets函数读取文件的每一行
				 // 读取文件内容
				while ((ch = fgetc(filePtr)) != EOF) {
					putchar(ch);
				}
				// 关闭文件
				fclose(filePtr);

				//readFile(driveLetter);

			}
		}
		else if ((DWORD)wp == DBT_DEVICEREMOVECOMPLETE)
		{
			DEV_BROADCAST_VOLUME* p = (DEV_BROADCAST_VOLUME*)lp;
			if (p->dbcv_devicetype == DBT_DEVTYP_VOLUME)
			{	
				int l = 65 + (int)(log(p->dbcv_unitmask) / log(2));
				MessageBox(NULL, TEXT("节点已拔出"), NULL, NULL);
			}
		}
		return TRUE;
	}
	else
		return DefWindowProc(h, msg, wp, lp);
}
int main()
{
	WNDCLASS wc;
	ZeroMemory(&wc, sizeof(wc));
	wc.lpszClassName = TEXT("myusbmsg");
	wc.lpfnWndProc = WndProc;

	RegisterClass(&wc);
	HWND h = CreateWindow(TEXT("myusbmsg"), TEXT(""), 0, 0, 0, 0, 0, 0, 0, GetModuleHandle(0), 0);
	MSG msg;
	while (GetMessage(&msg, 0, 0, 0) > 0)
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
}