C strtok_r 을 이용한 파일 내의 가입자 정보 읽어오기

readfile.c 는  strtok_r을 이용해 파일에 존재하는 가입자 정보를 불러오는 소스코드다.
sipd.conf 파일에 존재하는 가입자 정보를 불러와서 출력하지만 필요에 따라 가입자 정보를 load 하는 부분으로도 쓸 수 있을듯 하다. 그냥 만든것이므로 성능 및 안정성 장담 못함 ㅋㅋ

sipd.conf
------------------------------------------------------------------------
[you]
type=guest
username= you
host=127.0.0.1
secret=123456

[deoks]
type=friend
host=127.0.0.2
secret=987

[song]
type=gf
host=127.0.0.3
secret=45656

[hye112]
type=lover
host=127.0.0.4
secret=456

[23hye]
type=family
host=8.8.8.8.
secret=409809016



readfile.c


------------------------------------------------------------------------
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>



typedef struct sipd_st_UserInfo stp_sipd_user;
struct sipd_st_UserInfo{
char *type;
char *number;
char *username;
char *secret;
char *host;
};

void sipd_user_init(){
stp_sipd_user *user;

user = (stp_sipd_user*)malloc(sizeof(stp_sipd_user));

user->type = (char*)malloc(10);
user->number = (char*)malloc(10);
user->username = (char*)malloc(15);
user->secret = (char*)malloc(10);
user->host = (char*)malloc(15);
/*
user->type = NULL;
user->number = NULL;
user->username = NULL;
user->secret = NULL;
user->host = NULL;*/
}

void sipd_parse_users(char *info){
char *token;
char *ptr, *sub_ptr;
char *pri_delim="\n[]=";
char *sub_delim="\n=";
char t_name[20];
stp_sipd_user *user;
int n;

printf ("================\n[userinfo]\n%s\n================\n", info);

token = strtok_r(info, pri_delim, &ptr);
printf("username: %s\n",token);

while(token != NULL){
while(token != NULL){
// check either '=' or '\n'
token = strtok_r(NULL, sub_delim, &ptr);

if(token == NULL) break;


/* if token starts with '[', break to get next user info
could set user info at a struct. */
if(token[0] == '[')
break;

// get type info
if( strcmp(token,"type") == 0){
token = strtok_r(NULL, sub_delim, &ptr);
printf("type: %s\n",token);
}

// get secret info
else if( strcmp(token,"secret") == 0){
token = strtok_r(NULL, sub_delim, &ptr);
printf("secret: %s\n",token);
}

// get host info
else if( strcmp(token,"host") == 0){
token = strtok_r(NULL, sub_delim, &ptr);
printf("host: %s\n",token);
}
}
token = strtok_r(token, pri_delim, &sub_ptr);

/* Could set new user info here to a struct instead display */
if(token != NULL)
printf("username: %s\n",token);
}
}

int sipd_load_users()
{
FILE *fr;
int n;
long elapsed_seconds;
char line[100];
char info[800];

/* open the file for reading */
/* sipd.conf is the name of the file */
/* "rt" means open the file for reading text */
fr = fopen ("sipd.conf", "rt");

memset(info,0x00,sizeof(info));

while(fgets(line, 80, fr) != NULL)
{
strcat(info, line);
}
sipd_parse_users(info);

fclose(fr);  /* close the file prior to exiting the routine */
}

int main(){
sipd_user_init();
sipd_load_users();
return 0;
}

댓글 없음:

댓글 쓰기

안녕하세요 :)