foef 와 fgets

익명 사용자의 이미지

다음은 어떤 분이 짠 소슨데요.
이중에서 feof(fp) 가 왜 들어가야 되는지 모르겟어요..
제 의견으로는 한라인씩 읽어 나가는 것 같은데.
문제는 이걸 지워도 동작 잘 되거든요...

혹시 아시는 분 계십니까?

FILE *fp = fopen(CONFIG, "r");
if(fp == NULL)
{
exit(1);
}

while(!feof(fp) && fgets(p, 256, fp))
{
내용 생략....
}
fclose(fp);

익명 사용자의 이미지

..

익명 사용자의 이미지

새벽까지 안주무시고 답변을 써주셔서 감사합니다만,

저도 리눅스 게시판의 기본 예의 정도는 알고 있습니다만, ^^;
man foef 에서 feof 에 관한 내용은

함순 feof 는 stream이 가리키는 스트림을 위한 EOF 지시자를 검사하고,
만일 설정되어 있다면 0이 아닌 값을 반환한다. EOF 지시자는 clear-
err함수에 의해서만 지워질수 있다.

달랑 이부분 이군요..
솔직히 이거 보고 초보 프로그래머가 이해하기가 쉽지 않지 않습니까?

선배님들이 지나가다 쓴 3~4 줄 짜리 도움을 청하고자 글을 질문을 올린것이지,
조그만 노력도 없이 얻고자 한것은 아니라는 것을 말씀드리고 싶군요..

익명 사용자의 이미지

없어도 될듯하네요.

제가 쓰는 코드는

while( fgets( ... ) != NULL )
{
...
}

이걸 씁니다.

이전에는

fgets( ... )
while( !feof( ) )
{
Process;
fgets( ... )
}

이걸 썼는데... 이건 파일 형태에 따라서

마지막 줄을 못 읽는 경우가 있더군요 그럼 고운 하루되시길

익명 사용자의 이미지

맞는지 모르겠지만 아마도 ...

마지막 라인이 문제가 될 것 같습니다. fgets의 경우 \n 이거나 EOF가 나
올때까지 읽기 때문에 마지막이 \nEOF인 경우에 문제가 되지 않을까요?
EOF만으로 이루어진 라인이라면 계산에서 제외해야 될 것 같습니다.

즐거운 하루 되시기 바랍니다.

익명 사용자의 이미지

gets() and fgets() return s on success, and NULL on error or when end of file occurs while no characters have
been
read.

fgets 의 경우 NULL 을 리턴할때가 2가지 경우가

있습니다.

에러인 경우와... 화일의 끝인 경우인데요..

그것을 구분해 주기 위해서 feof 가 필요한

것입니다..^^.

익명 사용자의 이미지

comp.lang.c Frequently Asked Questions에 관련 내용이 있네요.^^

다음 페이지에 있습니다.

http//www.eskimo.com/~scs/C-faq/q12.2.html

그리고 상세 내용은 아래와 같습니다.

Question 12.2
Why does the code while(!feof(infp)) { fgets(buf, MAXLINE, infp);
fputs(buf, outfp); } copy the last line twice?

---------------------------------------------------------------------

In C, EOF is only indicated after an input routine has tried to
read, and has reached end-of-file. (In other words, C's I/O is not
like Pascal's.) Usually, you should just check the return value of
the input routine (fgets in this case); often, you don't need to use
feof at all.

References K&R2 Sec. 7.6 p. 164
ANSI Sec. 4.9.3, Sec. 4.9.7.1, Sec. 4.9.10.2
ISO Sec. 7.9.3, Sec. 7.9.7.1, Sec. 7.9.10.2
H&S Sec. 15.14 p. 382

1999년도에 iso에서 발표한 C언어의 새로운 표준인 일명, C99 표준에 의하
면,
the feof function tests the end of file indicator for the stream
pointed to by stream.
이라고 기술하고있습니다. 즉 eof의 존재 여부만을 검사하는 함수입니다.
즉 어느시점에서 eof를 검출하는지는 전혀 신경쓰지 않고 설계된 함수인
것입니다. (eof를 지난 시점에게야 eof를 감지하게됩니다.)
리턴 값과 관련된 기술내용은 다음과 같습니다.

the feof function returns nonzero if and if the end of file
indicator is set for stream

아래 소스내용은 제가 종종 사용하는 방식입니다.

while (isMoreData)
{
chk = fgets (buf, sizeof buf, inp);
if (!chk)
{
if (feof (inp))
{
printf ("At end-of-file!\n");
isMoreData = FALSE;
}
else if (ferror (inp))
{
printf ("Error during read\n");
/* determine if error is fatal. If so */
/* set isMoreData to FALSE, otherwise, */
/* try to move past it. */
}
else
{
printf ("Shouldn't get here!!!\n");
exit (0);
}
} /* Do stuff with input string */
}

익명 사용자의 이미지

feof는 데이터를 읽다가, end of file을 넘어선 이후의 시점에서 EOF를 인
식하기 때문에, EOF까지 데이터를 읽어 들이려고 하는 경우에 feof를 사용
하는 것은거의 모든 경우에 부적절합니다.
(feof함수가 EOF를 인식하는 시점에 주목하세요!!!)

올바로 EOF까지 데이터를 읽어들이는 동작을 구현하려면,
Fgets등 file에서 데이터를 읽어들이는 함수들의 리턴값을 기준으로
코드를 작성하는 것이 가장 적합한 방식입니다.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.