// cmd.cpp : 定义控制台应用程序的入口点。
// 目录下放一个txt文件 内容为ping 192.168.2.1 及可ping该网段下所有的ip
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <cassert>
#include <string>
using namespace std;
string readTxt(string file)
{
ifstream infile;
infile.open(file.data()); //将文件流对象与文件连接起来
assert(infile.is_open()); //若失败,则输出错误消息,并终止程序运行
string s;
while(getline(infile,s))
{
cout<<s<<endl;
break;
}
infile.close(); //关闭文件输入流
return s;
}
void writetxt(char * ss)
{
ofstream OutFile;
/*
ofstream OutFile; //实例一个写文件对象
OutFile.open("Test1.txt"); //创建一个Test.txt文本,并且打开Test.txt文件
//ofstream OutFile("Test.txt"); //利用构造函数创建txt文本,并且打开该文本
OutFile <<ss; //把字符串内容"This is a Test!",写入Test.txt文件
OutFile.close(); //关闭Test.txt文件
//return 0;
*/
OutFile.open("mytest.txt", ios::app);
if(!OutFile) //检查文件是否正常打开
{
cout<< "abc.txt can't open"<< endl;
abort(); //打开失败,结束程序
}
else
{
OutFile << ss;// << endl;
OutFile.close();
}
}
int _System(const char * cmd, char *pRetMsg, int msg_len)
{
FILE * fp;
char * p = NULL;
int res = -1;
if (cmd == NULL || pRetMsg == NULL || msg_len < 0)
{
printf("Param Error!\n");
return -1;
}
if ((fp = _popen(cmd, "r")) == NULL)
{
printf("Popen Error!\n");
return -2;
}
else
{
memset(pRetMsg, 0, msg_len);
//get lastest result
while (fgets(pRetMsg, msg_len, fp) != NULL)
{
printf("Msg:%s", pRetMsg); //print all info
}
if ((res = _pclose(fp)) == -1)
{
printf("close popenerror!\n");
return -3;
}
pRetMsg[strlen(pRetMsg) - 1] = '\0';
return 0;
}
}
//char *cmd ;
int getpos(char s[],int star,int len)
{
for(int i=len;i>5;i--)
if (s[i]=='.')
return i;
return 1;
}
char dd[20] ="ping 127.1.30.1";
int _tmain(int argc, _TCHAR* argv[])
{
//test cmd
string ipset;
ipset=readTxt("ip.txt");//会自动ping txt文件中设置的ip所在的网段
ipset.copy(dd,20,0);
int posofpoint= getpos(dd,13,20);
//char *cmd = "python d:\\PythonProjects\\Demo1.py [1]";
for (int i=1;i<254;i++)
{
char *cmd = "1";
char u;
char buffer[65];
_itoa( i, buffer, 10); //正确解法一
printf("zzzz%css%css%c",dd[10],dd[11],dd[12]);
dd[posofpoint+1]=buffer[0];
dd[posofpoint+2]=buffer[1];
dd[posofpoint+3]=buffer[2];
//strcat(dd,buffer);
char a8Result[128] = { 0 };
int ret = 0;
ret = _System((char *)dd, a8Result, sizeof(a8Result));
printf("ret = %d \na8Result = %s\nlength = %d \n", ret, a8Result, strlen(a8Result));
char result_[100];
//sprintf(result_, "%d", 123);
sprintf(result_,"%s\t ret = %d \na8Result =%s \nlength = %d \n",dd,ret,a8Result, strlen(a8Result));
writetxt((char *)result_);
}
getchar();
return 0;
}