用C程序自动打开电脑上的程序

打开记事本上所写的程序

在这里插入图片描述
如图所示,我在记事本上写下了三个程序,我怎样才可以用程序打开这三个程序呢?
答案是:用createProcess函数
在这里插入图片描述

实践

#include<stdio.h>
#include<Windows.h>
#define MaxProcCount 10
#define MAX_LINE_LEN 80

int main(void)
{
	FILE* CommandFile;
	char cmdLine[MaxProcCount][MAX_LINE_LEN];
	char tempLine[MAX_LINE_LEN];
	int realProcCount = 0;

	if (fopen_s(&CommandFile,"./commandText.txt", "a+"))
	{
		printf("open failed");
		exit(1);
	 }
	while (fgets(tempLine, MAX_LINE_LEN, CommandFile) != NULL)
	{
		char x = tempLine[strlen(tempLine)-1];
		if (x == '\n')
		{
			strncpy_s(cmdLine[realProcCount++], tempLine, strlen(tempLine) - 1);
		}
		else 
		{
			strncpy_s(cmdLine[realProcCount++], tempLine, strlen(tempLine));
		}
	}
	for (int i = 0; i < realProcCount; i++)
	{
		STARTUPINFO startInfo = { sizeof(startInfo) };
		PROCESS_INFORMATION procInfo;
		startInfo.dwFlags = STARTF_USESHOWWINDOW;
		startInfo.wShowWindow = TRUE;
		bool success = CreateProcess(
			NULL,									//不在此指定可执行文件的文件名
			cmdLine[i],								//命令行参数
			NULL,									//默认进程安全性
			NULL,									//默认进程安全性
			TRUE,									//指定当前进程内句柄可以被子进程继承
			CREATE_NEW_CONSOLE,						//为新进程创建一个新的控制台窗口
			NULL,									//使用本进程的环境变量
			NULL,									//使用本进程的驱动器和目录
			&startInfo,
			&procInfo
		);
		if (success)
		{
			CloseHandle(procInfo.hThread);
			CloseHandle(procInfo.hProcess);
		}
	}
	fclose(CommandFile);
	getchar();
	return 0;
}

成果

在这里插入图片描述

发布了43 篇原创文章 · 获赞 16 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/include_IT_dog/article/details/89435068