WIN平台下应用程序利用批处理更新自身

今天又碰到需要做一个简单的自动升级的客户端程序,

客户端程序在拿到升级包并且解压之后,怎样自更新并再启动呢?

这里我封装了一个类,利用批处理,将升级文件覆盖掉本地文件,然后重启动应用程序。

 

#ifndef KILL_MYSELF_H_
#define KILL_MYSELF_H_

#include <iostream>
#include <vector>

class UpdateMyself
{
public:
	UpdateMyself()
	{
		m_Files.clear();
	}

	//设置更新目录
	void SetDir( std::string dir )
	{
		m_UpdateDir = dir;
	}

	//增加更新文件
	void AddFile( std::string filename )
	{
		m_Files.push_back( filename );
	}

	//设置启动应用名
	void SetStartApp( std::string appname )
	{
		m_StartApp = appname;
	}

	//执行
	void Execute()
	{
		//建立更新批处理文件
		FILE *fp; 
		fp = fopen( "update.bat" , "w+" ); 
		fprintf( fp , "@echo off\n" ); 
		
		//覆盖本地文件
		for( std::vector<std::string>::iterator iter = m_Files.begin(); iter != m_Files.end(); ++iter )
		{
			std::string filename = *iter;
			fprintf( fp , "del %s\n", filename.c_str() ); 
			fprintf( fp , "copy .\\%s\\%s %s\n", m_UpdateDir.c_str(), filename.c_str(), filename.c_str() ); 
			fprintf( fp , "del .\\%s\\%s\n", m_UpdateDir.c_str(), filename.c_str() ); 
		}

		//自杀
		fprintf( fp , ":begin\n" ); 
		fprintf( fp , "del %s\n", m_StartApp.c_str() ); 
		fprintf( fp , "if exist %s goto begin\n", m_StartApp.c_str() ); 
		fprintf( fp , "copy .\\%s\\%s %s\n", m_UpdateDir.c_str(), m_StartApp.c_str(), m_StartApp.c_str() ); 
		//fprintf( fp , "rd/q %s\n", m_UpdateDir.c_str() );
		fprintf( fp , "del .\\%s\\%s\n", m_UpdateDir.c_str(), m_StartApp.c_str() ); 
		fprintf( fp , "start %s\n", m_StartApp.c_str() );
		fprintf( fp , "del %%0%%\n");
		fclose(fp); 

		WinExec("update.bat",SW_SHOW);
		exit(0);
	}
private:
	std::vector<std::string> m_Files;
	std::string m_UpdateDir;
	std::string m_StartApp;
};

#endif

 

 

假设我们下载之后的更新文件都位于update目录中,我只需要

 

UpdateMyself test;

test.SetDir("update");

test.AddFile(...);  把要更新的文件名加进去

test.SetStartApp(...); 设置更新之后启动的应用程序名称

test.Execute();

 

就可以完成更新了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值