#include "ipslt.h" #define MAXSIZE 32000 string strIp[MAXSIZE]; int cmp( const void *a , const void *b ) //字符串比较函数 { string c, d; c = *(string *)a; d = *(string *)b; return c.compare(d); } void readfile(ifstream &infile, int *ret1, int *ret2) //读文件到strIp数组中去 { int i = 0,EndOfFile = 0; for (i; i<MAXSIZE; i++) { if(getline(infile,strIp[i])) //读取一行并赋值给strIp[i] { continue; }else { //如果读到文件末尾,标准“EndOfFile”赋值为1,并退出循环 EndOfFile = 1; break; } } *ret1 = i; *ret2 = EndOfFile; } void main(int argc, char **argv) { int i = 0 ,j, ret1 = 0, ret2 = 0, len = 0; char newname[256]; memset(newname, 0, sizeof(char)*256 ); len = strlen(argv[1]) - 4; strncpy(newname, argv[1], len); strcat(newname, "_result.txt"); FILE *filein; if(NULL == (filein = fopen(argv[1], "r"))) printf("open the %s fail !/n",argv[1]); cout << "waiting......" << endl; ipSelect1(argv); //调用函数ipSelect1后会生成temp_1文件 ifstream infile("temp_1"); //打开temp_1文件 ofstream outfile("temp_2"); //生成temp_2文件,当调用readfile函数时对其进行写操作 while (1) { readfile(infile, &ret1, &ret2); //调用readfile函数 i = ret1; qsort(strIp, i, sizeof(string), cmp); //对strIp字符串数组进行排序 for(j=0; j < i; j++) //将排序后的结果写入result.txt文件 { outfile << strIp[j] << endl; cout << strIp[j] << endl; } if (ret2 == 1) //判断是否已经读完目标文件 { cout << "finish." << endl; break; } } infile.close(); //关闭temp_1文件 outfile.close(); //关闭temp_2文件 ipSelect2(newname); unlink("temp_1"); //删除生成的中间结果文件 unlink("temp_2"); //删除生成的中间结果文件 system("pause"); } ipslt.h文件: #include <string> #include <iostream> #include <fstream> #include <stdlib.h> using namespace std; void ipSelect1(char **argv) { char temp1[256], temp2[256], temp3[256], temp5[256], newname[256]; char *temp4 = "."; FILE *fpr, *fpw; int i = 0, j = 0; memset(newname, 0, sizeof(char)*256 ); if(NULL == (fpr = fopen(argv[1], "r"))) printf("open the %s fail !/n",argv[1]); if(NULL == (fpw = fopen("temp_1", "w"))) printf("creat the 'temp_1' fail !/n"); do { memset(temp1, 0, sizeof(char)*256 ); if(NULL == fgets(temp1,256,fpr)) break; while (i < 3 && j < 13) //提取temp1的前3个ip字段,包含最后一个点号 { if(temp1[j] == *temp4) i++; j++; } if (i == 3 && j < 13) { memset(temp2, 0, sizeof(char)*256 ); strncpy(temp2,temp1,j); //获得temp1的前3个ip字段存放在temp2变量中 if (strcmp(temp2,temp3)) { memset(temp3, 0, sizeof(char)*256 ); strcpy(temp3,temp2); fprintf(fpw, "%s1-%s255/n", temp3,temp3); } }else{ //去除非ip格式的相邻重复项 if (strcmp(temp1,temp5)) { memset(temp5, 0, sizeof(char)*256 ); strncpy(temp5,temp1,256); fprintf(fpw, "%s",temp1); } } j = 0; i = 0; } while(1); fclose(fpr); fclose(fpw); } void ipSelect2(char *ResultName) { string s1, s2; ifstream fin("temp_2"); ofstream fou(ResultName); while (getline(fin, s1)) { if (s1.compare(s2)) { s2 = s1; fou << s1 << endl; } } fin.close(); fou.close(); }