#include #include #include #define HTTP_FLAG 0 #define IP_FLAG 1 typedef struct ipaddress { short int int1, int2, int3, int4; } ipaddress; typedef struct logStruct { ipaddress ip; int http; char * logline; } logType; void getIP(ipaddress * ip, char * logline) { ip->int1 = atoi(strtok(logline, ".")); ip->int2 = atoi(strtok(NULL, ".")); ip->int3 = atoi(strtok(NULL, ".")); ip->int4 = atoi(strtok(NULL, " ")); return; } void getHTTP(int * http, char * logline) { strtok(logline, "\""); strtok(NULL, "\""); http[0] = atoi(strtok(NULL, " ")); return; } int compare(logType * line1, logType * line2, int flag) { if (flag == HTTP_FLAG) return (line1->http - line2->http); if (line1->ip.int1 != line2->ip.int1) return (line1->ip.int1 - line2->ip.int1); if (line1->ip.int2 != line2->ip.int2) return (line1->ip.int2 - line2->ip.int2); if (line1->ip.int3 != line2->ip.int3) return (line1->ip.int3 - line2->ip.int3); return (line1->ip.int4 - line2->ip.int4); } void bubbleSort(logType * * array, int length, int flag) { logType * tempPointer; for (int i = 0; i < length-1; i++) for (int j = 0; j < length-1; j++) { if (compare(array[j],array[j+1],flag)>0) { tempPointer = array[j]; array[j] = array[j+1]; array[j+1] = tempPointer; } } return; } int main(void) { char buffer[500]; FILE * weblog; FILE * outFile; int numLines = 0; int sortMethod = 0; logType * * sortArray; weblog = fopen("friedspace.txt","r"); while (!feof(weblog)) { numLines++; fgets(buffer,500,weblog); } rewind(weblog); sortArray = calloc(sizeof(logType *) , numLines); for (int counter = 0; counter < numLines; counter++) { sortArray[counter] = calloc(sizeof(logType),1); sortArray[counter]->logline = calloc(sizeof(char),500); fgets(sortArray[counter]->logline,500,weblog); strcpy(buffer,sortArray[counter]->logline); getIP(&(sortArray[counter]->ip),buffer); strcpy(buffer,sortArray[counter]->logline); getHTTP(&(sortArray[counter]->http),buffer); } printf("Do you want the data sorted by 0: HTTP code, or 1: IP address? "); scanf("%d",&sortMethod); bubbleSort(sortArray, numLines, sortMethod); outFile = fopen("sorted.out", "w"); for (int i = 0; i < numLines; i++) { fputs(sortArray[i]->logline,outFile); } fclose(weblog); fclose(outFile); return 0; }