끄적끄적

반응형

feof(),,, 마지막 줄 두 번 안 읽게 하는 처리



data 파일의 내용

Hanyang University

The College of Information and Communication

Major in Computer

(줄바꿈)


라고 가정하고,

fread() 함수로 data 파일의 내용을 읽어 오면


Hanyang University

The College of Information and Communication

Major in Computer

Major in Computer


이렇게 맨 마지막줄이 한 번 더 출력되는 상황이 발생한다.

이럴 때는 어떻게 대처해야 할까?


아래와 같이 fread() 함수로 한 번 더 읽어서 fread() == 0 임을 판단 하여 TRUE 값을 반환 한다면 break로 루프를 빠져 나오게 처리하면 된다.


while(!feof(fp)) {

if(fread(&buf, 1, 1, fp) == 0) break;

// 또는 if(fread(&buf, 1, 1, fp) == NULL) break;

else fseek(fp, -1, SEEK_CUR);

// 파일의 끝인지 확인하기 위해 1byte만큼 읽었으므로

// 파일포인터를 다시 1byte만큼 앞으로 되돌린다.

}

반응형
Please Enable JavaScript!
Mohon Aktifkan Javascript![ Enable JavaScript ]