이글은 예전 제 싸이월드 블로그에 작성한 글을 티스토리로 옮긴 것입니다.
원문 : http://cy.cyworld.com/home/21147242/post/536C959E2BD5739A07C68401
원문 작성일 : 2014.5.9
============================================================
예전에 만들어 본 기억이 있는데 다시 만드니 삽질...
예방차원에서 올려놓는다.
1. test.dat 파일엔 2 ~ 97 사이의 임의의 숫자 34개가 개행문자 없이 저장되어 있다.
->2 bytes 단위로 읽어들이면 저장된 값을 가져올 수 있음.
2. 주어진 값(int target ) 이 test.dat 에 존재하는지 찾는 것을 목적으로 한다.
* int getCount() : test.dat 파일에 몇개의 값이 있는지 계산하여 반환한다.
* 첨부파일 : main.cpp, Makefile, test.dat
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
72
73
74
75
76
77 |
#include <cstdio>
#include <cstdlib>
#define FILE_NAME "./test.dat"
static FILE* fp ;
int getCount(int width)
{
fp = fopen(FILE_NAME, "rt") ;
fseek(fp, 0, SEEK_END) ;
return (ftell(fp) / width ) ;
}
int main()
{
int width = 2 ;
int count ;
static char szText[128] ;
count = getCount(width) ;
int fileVal, target ;
int leftPos, midPos, rightPos ;
fp = fopen(FILE_NAME, "rt") ;
for(int ii = 2; ii <= 97; ii++)
{
leftPos = 0 ;
rightPos = count - 1 ;
target = ii ;
// bisection.
while(1)
{
midPos = (leftPos + rightPos) / 2 ;
fseek(fp, midPos * width, SEEK_SET) ;
fread(szText, width, 1, fp) ;
szText[width] = '\0' ;
fileVal = atoi(szText) ;
if(fileVal == target) // find
break ;
if(leftPos == rightPos) // cannot found
break ;
if(rightPos - leftPos == 1)
{
if(midPos == leftPos)
leftPos++ ;
else
rightPos-- ;
continue ;
}
leftPos = (target > fileVal) ? midPos : leftPos ;
rightPos = (target <= fileVal) ? midPos : rightPos ;
}
if(fileVal == target)
printf("find ; %d\n", target) ;
else
printf("Cannot find ; %d\n", target) ;
}
fclose(fp) ;
return 1 ;
}
|
'삽질미학 > C,C++' 카테고리의 다른 글
string class를 이용한 Big Integer(BigInt) 계산기 구현 (0) | 2017.01.09 |
---|---|
파일값을 이용한 bisection search - class (0) | 2017.01.09 |
printf() 에서 "%nd" 에서 n값을 변수로 대체하기. (0) | 2017.01.09 |
STL set 컨테이너에 2차원 배열 삽입하기 (0) | 2017.01.09 |
STL set 컨테이너에 구조체 삽입하기 (0) | 2017.01.09 |