Abnormal behavior to handle text files in C -


i'm trying simulate behavior of dns server, have db named hosts.txt containing machine_names/ip_addresses, example:

equipo_00/169.0.1.169 sala_oeste_01/200.1.2.200 sala_oeste_02/200.2.3.200 sala_oeste_03/200.3.4.200 memfis_04/201.4.5.201 icaro_05/200.5.6.200 equipo_06/169.6.7.169 sala_este_07/201.7.8.201 sala_este_08/201.8.9.201 cec_09/189.9.10.189 

here's code:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h>  int main(int argc, char** argv) {     char* machine, *ip_add;     file* db;     char* flag;     char  tmp[256];     char  par[256];     printf("> ");     scanf("%s", par);     db = fopen("hosts.txt", "r");     while(db != null && fgets(tmp, sizeof(tmp), db) != null)     {         if(strstr(tmp, par))         {             flag = "1"; // flag setting 1 means find line             machine = strtok(tmp, "/");//here's supposed value of machine             ip_add = strtok(null, "/");//here's supposed value of ip adress         }     }//while      if(strcmp(flag, "1") == 0) //     {         printf("here\n");     }     else     {         flag = "0"; //flag setting 0         printf("there\n");     }      printf("flag= %s pc=%s server=%s\n", flag, machine, ip_add);     return 0; } 

my code reads standard input, value of machine , indicate ip address assigned machine on server. problem program not normal behavior, not know how modify code expected output, eg

input: equipo_00 output: flag = 1 pc = equipo_00 server=169.0.1.169 

sorry if question rather silly, i'm new language .. thank , excuse english

this do:

read string file tmp.

check if user entered string par present in tmp.

if yes go ahead , tokenize tmp on / , make pointer machine point first piece , ip_add point next piece.

note machine , ip_add just pointers. , point @ various indices of tmp. later when continue loop read new string again into tmp, overwriting it. causes problem , pointer pointing changed string.

to avoid add break after successful match:

if (strstr(tmp, par)) {    flag = "1";    machine = strtok(tmp, "/");    ip_add = strtok(null, "/");    break;        } 

also final printf:

printf("flag= %s pc=%s server=%s\n", flag, machine, ip_add); 

should part of if body, print them if you've found match. printing if match not found. in case you'll printing junk pointers server , ip_add have not been initialized.


Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

400 Bad Request on Apache/PHP AddHandler wrapper -

php - Change action and image src url's with jQuery -