Boost. program_options初探+openssl计算文件MD5值

Boost. program_options介绍

程序参数项(program options)是一系列name=value对,program_options 允许程序开发者获得通过命令行(command line)和配置文件(config file)获取这些参数项。

为什么需要这样一个库?为什么比你手工写代码分解命令行参数要好?

        1、使用更容易。定义参数处理的语法简单,库自身很小。像转换参数值到指定的类型和保存参数值到变量的事情都是自动处理。 

        2 、错误报告更友好。可报告错误的命令行参数。另外这个库能自动生成使用帮助,避免手工更新使用帮助导致的不一致。 

        3、参数能从不同地方读取。当命令行参数不能满足要求,需要改用配置文件或环境变量。

初次使用Boost刚开始觉得代码有点难度,一遍又一遍的才有了初步的了解。

与我另外一篇文章不同的是我改用C++文件操作,即fstream

#include <iostream> 
#include <openssl/md5.h> 
#include <string>
#include <fstream>
#include <openssl/sha.h> 
#include <boost/program_options.hpp>
#pragma comment(lib, "libeay32.lib")
#pragma comment(lib, "ssleay32.lib")
 
typedef  std::ifstream  IFS;
namespace po = boost::program_options;

int main(int argc,char *argv[])
{
    int len = 0;
    unsigned char buffer[1024] = {0};
    char *fname;//用于存放文件名
    IFS file;

    po::options_description desc("Allowed options");//帮助项  
    desc.add_options()  
        ("help,h", "produce help message")  
        ("md5", po::value<std::string>(), "output md5 of file")
	("sha1",po::value<std::string>(), "output sha1 of file");  
  
    po::variables_map vm;  
    po::store(po::parse_command_line(argc, argv, desc), vm);  
    po::notify(vm);  

    if(vm.count("help"))  
    {  
        std::cout<<desc<<std::endl;  
        return 1;  
    }  
  
    if(vm.count("md5"))    //计算md5
    {  
        fname=(char*)vm["md5"].as<std::string>().data();//将文件路径由string转为char*
	file.open(fname);
	MD5_CTX ctx = { 0 };
	unsigned char digest[16] = {0};
	MD5_Init (&ctx);

	while (!file.eof()) {
            file.read((char*)buffer, 1024);
            len = file.gcount();
            if (len > 0)
            MD5_Update (&ctx, buffer, len);
        }

	MD5_Final (digest, &ctx);
	file.close();
	char buf1[33] = {0};
	char tmp1[3] = {0};
	for(int i = 0; i < 16; i++ )
	{
		sprintf(tmp1,"%02X", digest[i]); 
		strcat(buf1, tmp1); 
	}
        std::cout <<buf1 << std::endl;
     }
     else if(vm.count("sha1")){     //计算sha1
         fname=(char*)vm["sha1"].as<std::string>().data();
	 file.open(fname);

	 SHA_CTX c ={ 0 };  
         unsigned char md[20] = {0}; 
	 SHA1_Init(&c); 

	 while (!file.eof()) {
             file.read((char*)buffer, 1024);
             len = file.gcount();
             if (len > 0)
             SHA1_Update (&c, buffer, len);
         }

	 SHA1_Final(md, &c); 
	 file.close();
	 char buf2[41] = {0};  
	 char tmp2[3] = {0}; 
	 for(int i = 0; i < 20; i++ )  
	 {  
	     sprintf(tmp2,"%02X", md[i]);  
	     strcat(buf2, tmp2);  
	 }  
	 std::cout << buf2 <<std::endl;  
    }
    else  
   {  
         std::cout<<"error"<<std::endl;  
    }  
	return 0;
}


发布了20 篇原创文章 · 获赞 25 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/Timekeeperl/article/details/50612320