Linux下使用代码调用命令行

来源:互联网 发布:360软件认证中心 编辑:程序博客网 时间:2024/06/01 23:13
//核心函数:popen
#include <stdio.h>#include <string.h>#include "Hzhy_Rtc.h"static char cmd_get_tm[] = "date \"+%Y-%m-%d %H:%M:%S\"";//应答格式:2013-02-19 13:14:19static char cmd_set_tm[8] = "date -s ";//date -s "2016-10-13 14:46:00"//-------------------------------------------------------------------//功能:获取时间//输入://输出://备注://-------------------------------------------------------------------int GetTime(USER_TIME *tm){FILE *fp;char buf[80];fp = popen(cmd_get_tm,"r");fgets(buf,sizeof(buf),fp);printf("Get:%s",buf);pclose(fp);//应答格式:2013-02-19 13:14:19tm->year = (buf[0]-0x30)*1000 + (buf[1]-0x30)*100 + (buf[2]-0x30)*10 + (buf[3]-0x30);tm->month = (buf[5]-0x30)*10 + (buf[6]-0x30);tm->day = (buf[8]-0x30)*10 + (buf[9]-0x30);tm->hour = (buf[11]-0x30)*10 + (buf[12]-0x30);tm->min = (buf[14]-0x30)*10 + (buf[15]-0x30);tm->sec = (buf[17]-0x30)*10 + (buf[18]-0x30);printf("%04d-%02d-%02d %02d:%02d:%02d\n",tm->year,tm->month,tm->day,tm->hour,tm->min,tm->sec);return 0;}//-------------------------------------------------------------------//功能:设置时间//输入:buf[0~5]:年月日时分秒(年=实际值-2000)//输出:0:成功!0:失败//备注://-------------------------------------------------------------------int SetTime(USER_TIME set){FILE *fp;char buf[80],tm[40];memset(buf,0,sizeof(buf));memset(tm,0,sizeof(tm));sprintf(buf,cmd_set_tm);sprintf(tm,"\"%04d-%02d-%02d %02d:%02d:%02d\"",set.year,set.month,set.day,set.hour,set.min,set.sec);strcat(buf,tm);printf("Set:%s",buf);fp = popen(buf,"r");pclose(fp);return 0;}

0 0
原创粉丝点击