Expected file format...
1,s,2,3,4,5
1,r,6,7,8,9
2,s,1,3,4,5
2,r,6,78,8,9
#include <stdio.h>
#define NODE_ROUTING_FILE "node_routing"
#define MAX_PEERS 100
int read_line(FILE* the_file, char* the_buf)
{
int done = 0;
char this_char;
int ret_code = 0;
while (!done)
{
if (!fread(&this_char, 1, 1, the_file))
{ ret_code = 1;
done = 1;
}
else
{ if (this_char == '\n')
{ done = 1;
}
else
{ *the_buf++ = this_char;
} } }
*the_buf = 0;
return ret_code;
}
/* return '1' if no comma found
*/
int get_next_string(char* the_line, char* buf)
{
int done = 0;
char this_char;
int ret_code = 0;
char* ptr = the_line;
while (!done)
{ if (*ptr == ',')
{ *buf = 0;
done = 1;
}
else if (*ptr == 0)
{ *buf = 0;
return -1;
}
else if (*ptr != ' ')
{ *buf++ = *ptr;
}
ptr++;
}
return ptr - the_line;
}
int process_line(char* the_line, int my_id, int* send_to, int* rcv_from)
{
int done = 0;
char this_char;
char this_string[100];
int this_id;
int send_mode = 0;
int offset = 0;
int stage = 0;
int peers_stored = 0;
while (!done)
{ offset = get_next_string(the_line, this_string);
if (offset == -1)
{ done = 1;
}
else
{ the_line += offset;
}
if (stage == 0)
{ stage++;
this_id = atoi(this_string);
if (my_id != this_id)
{ return 0;
} }
else if (stage == 1)
{ stage++;
if (this_string[0] == 's' || this_string[0] == 'S')
{ send_mode = 1;
}
else if (this_string[0] == 'r' || this_string[0] == 'R')
{ send_mode = 0;
}
else
{ printf("??? %s ??? list\n", this_string[0]);
return 0;
}
}
else
{ if (send_mode)
{ *send_to++ = atoi(this_string);
}
else
{ *rcv_from++ = atoi(this_string);
}
peers_stored++;
}
}
return peers_stored;
}
/* returns 1 if fails
*/
int process_file(char* file_name, int id, int* send_to, int* rcv_from)
{
FILE *input_file;
int i;
char this_line[400];
int done = 0;
int read_status;
for (i = 0; i < MAX_PEERS; i++)
{ send_to[i] = 0;
rcv_from[i] = 0;
}
input_file = fopen(file_name, "r");
if (input_file == NULL)
{ printf("Can't open node routing file '%s'\n", NODE_ROUTING_FILE);
return 1;
}
while (!done)
{ read_status = read_line(input_file, this_line);
if (read_status)
{ done = 1;
}
else
{ process_line(this_line, id, send_to, rcv_from);
}
}
return 0;
}
int main(void)
{
int send_to[MAX_PEERS];
int rcv_from[MAX_PEERS];
int i;
int my_id = 2;
int result;
result = process_file(NODE_ROUTING_FILE, my_id, send_to, rcv_from);
if (result)
{ printf("File parsing failure\n");
return 1;
}
printf("id %d sends to: ", my_id);
i = 0;
while (send_to[i])
{ printf("%d, ", send_to[i]);
i++;
}
printf("\n");
printf("id %d receives from: ", my_id);
i = 0;
while (rcv_from[i])
{ printf("%d, ", rcv_from[i]);
i++;
}
printf("\n");
}
--
MattWalsh - 16 Sep 2004