티스토리 뷰

프로그램 설계

프로그램 개요

  • 주소록 관리를 위하여 파일에 보관되며 검색 ∙ 수정 ∙ 삭제가 가능한 시스템 구현
  • 유효성 검사를 위하여 다양한 라이브러리 함수를 사용할 수 있음
  • 프로그램의 기능 수행을 위한 요구분석을 주의 깊게 수행해야 함
  • 현재 시간 등을 반홖하는 함수로 time 함수를 이용할 수 있음
  • 이진파일의 입출력은 fread, fwrite를 이용할수 있음

기능

프로그램 구현 시 처리 대상 자료

  • 이름
  • 생년월일
  • 주소
  • 나이
  • 전화번호

기능 정의

  • 주소록 보기
  • 등록, 검색
  • 수정, 삭제
  • 종료

기능 정의

  • 주소록 입력
  • 주소록 출력
  • 주소록 검색
  • 나이 자동계산

자료구조 정의

structphone {
   char name[20];
   char phone[14];
   intbirth;
   intage;
   char addr[50];
};

 

코드 분석

  • 검색 문자의 위치를 찾을 수 있는 함수: strchr
  • 문자열의 길이를 반홖하는 함수 : strlen
  • 현재 시간 정보를 얻을 수 있는 함수 : time
  • 이진 파일의 읽기와 쓰기에 이용하는 함수 : fread, fwrite

입력 검증 : 데이터를 입력하지 않고 넘어가는 경우를 검사

while(1){
  fflush(stdin);
  printf("\n이름 : ");
  gets(mp[cnt].name);
  if ( strlen(mp[cnt].name) > 0 )
  	break;
  printf("\n이름을 입력하세요 ");
}

 

 

 

숫자 입력인지 확인

while(1){
  fflush(stdin);
  printf(“출생연도 : ”);
  scanf(“%d”,&mp[cnt].birth);
  if ( mp[cnt].birth > 0 ) 
  	break;
}

 

나이 계산

int calAge(int birth){
   time_t timer;
   struct tm *t;
   timer = time(NULL); 
   t = localtime(&timer); 
   return t->tm_year + 1900- birth;
}

 

파일 쓰기 : 이전 데이터 파일 쓰기

void savePhones(PHONE* mp, int cnt)
{ 
	FILE * fp;
    int i;
    fp = fopen ("myPhones.bin" , "wb+");
    if (fp == NULL) perror (‚Error opening file‛);
    else {
      fwrite(&cnt, sizeof(int), 1, fp);
      fwrite(mp, sizeof(PHONE), cnt, fp);
      fclose (fp); 
    }
}

파일 읽기

PHONE* readPhones(PHONE* mp, int* cn){
   FILE * fp;
   int i,cnt;
   cnt = *cn;
   fp = fopen ("myPhones.bin" , "rb+");
   if (fp == NULL) perror ("Error opening file");
   else {
     fread(&cnt, sizeof(int),1,fp);
     mp = (PHONE*)realloc(mp,sizeof(PHONE)*(cnt+1)); 
     fread(mp, sizeof(PHONE), cnt, fp);
  	 fclose (fp); 
  }
   *cn = cnt;
   return mp; 
}

데이터 수정

PHONE* modifyPhone(PHONE* mp, inti){
	char yn;
	intsel;
	printf("\n-----------------------------------");
	printf("\n1. 이 름: %s \n",mp[i].name);
	printf("2. 젂화번호: %s \n",mp[i].phone);
	printf("3. 주 소: %s \n",mp[i].addr);
	printf("4. 출생연도: %d \n",mp[i].birth);
	printf("나 이: %d \n",mp[i].age);
	printf("\n-----------------------------------");
	printf("\n수정할데이터를선택하세요: ");
	scanf("%d",&sel);
	switch(sel){
		case 1 : 
			while(1){
			fflush(stdin);
			printf("\n이름: ");
			gets(mp[i].name);
	if ( strlen(mp[i].name) > 0)
		break;
		printf("\n이름을입력하세요");
	}
	break;
댓글