Thursday, November 20, 2014

Linear Search in C

Hit a wall with PicoCTF so I'm taking a break. I found a program for a linear search in C on Programming Simplified:
This gave me the idea for a program that could parse information, store it in structs to categorize it, then later be searched using the Linear Search. The program I came up with doesn't read files only accepts user input:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//Set global variable
int totalmembers = 0;
//Declare struct and set variables in struct
struct file{
char name[30];
char state[4];
char age[3];
};
//Declare single structure within struct as an array
struct file members[50];
//Declare function to add members
void MemberAdd(void)
{
 int ctr;
 int addmember = 1;
 char moremembers[4];
//For loop to store input by user in variables in struct array
for (ctr=0; ctr < addmember; ctr++)
{
 printf("Please enter a member\n");
 scanf("%s", members[ctr].name);
 printf("Where does this member live?\n");
 scanf("%s", members[ctr].state);
 printf("What's this member's age?\n");
 scanf("%s", members[ctr].age);
 getchar();
 totalmembers++;
 printf("Do you have more members to input?\n");
 scanf("%s", moremembers);
 if (strcmp(moremembers, "yes")==0)
 {
  addmember++;
 }
 else
 {
  break;
 }
}
}

int main()
{

char search[10];
int c;
int matches = 0;

MemberAdd();


   printf("Enter the criteria to search\n");
   scanf("%s", search);

   for (c = 0; c < totalmembers; c++)
   {
    //If records are found in struct
      if ((strcmp(members[c].name, search) == 0) || (strcmp(members[c].state, search) == 0) || (strcmp(members[c].age, search) == 0))
      {
         printf("%s is present in record %d.\n", search, c+1);
         printf("Record %d: %s %s %s\n", c+1, members[c].name, members[c].state, members[c].age);
         matches++;
      }
   }
   if (matches == 0)
      printf("%s is not present in records.\n", search);

   return 0;
}
It's not the prettiest code but, if you substituted the function to take inputs with one that reads files and sticks the relevant info into the structs and switched out the placeholder code for the name, state, and age with whatever categories you needed, I'm thinking you could maybe use it for quick one off analyses and search of results.  Easier said than done but I'm going to try it on some log files.

No comments:

Post a Comment