שאלה על ()feof

פIלי

New member
שאלה על ()feof

יש לי בעיה, משום מה feof לא מוצא אצלי את סוף הקובץ בזמן, אלא רק אחרי שקראתי את המחרוזת האחרונה בקובץ פעמיים. לדוגמא חלק מקוד קטן שכתבתי:
while( !feof() ) { fgets(buf,100,fp); printf("%s", buf); }​
(buf מוגדר כמערך של 100 צ´ארים ו fp הוא מצביע לטיפוס FILE, שפתוח בקובץ temp.txt) הבעיה היא שזה מציג את הקובץ temp.txt בסדר, אבל מציג את השורה האחרונה פעמיים. אני משתמש בקומפלייר Zortech C (בא עם הספר המאוד ישן שלי). למישהו יש פתרון?
 

DCoder

New member
שנה את סדר הפעולות

feof(FILE *stream) returns a non-zero value after EOF is reached, and not before. Let´s take the following file: First line Second line Now, when fgets reads ´Second line´, it prints it, and feof() still returns 0. Next, fgets tries to read the next line and encounters EOF. However, you still print buf, which is probably unchanged. Instead, this should work ( unchecked ): fgets(buff, 100, fp); while(!feof(fp)){ printf("%s", buf); fgets(buf, 100, fp); } Of course, this would only work when the last line ends with ´\n´. ( assuming lengths of all lines < 100 )​
 

ke

New member
למה לא ככה ?

feof מחזירה Non-zero אם היה נסיון קריאה אחרי ה end-of-file, ואת זה אפשר לקבל כאינדיקציה הערך החזרה של fgets שמחזירה 0 אם הגיעה לסוף קובץ או אם היתה טעות (ואז משתמשים ב feof לבחור מה - תסתכל למשל בתיעוד של msdn). כלומר אפשר לכתוב :
#include <stdio.h> int main() { FILE* fp = fopen("aaa.txt","r"); char buf[100]; while( fgets(buf,100,fp) ) { printf("%s",buf); } return 0; }​
ואם רוצים לבדוק עם feof אז אפשר לכתוב :
#include <stdio.h> int main() { FILE* fp = fopen("aaa.txt","r"); char buf[100]; while( fgets(buf,100,fp) ) { printf("%s",buf); } if (feof(fp)) { printf("Reached end of file\n"); } else { printf("Some error occured while reading...\n"); } return 0; }​
מהתיעוד של MSDN Return Value Each of these functions returns string. NULL is returned to indicate an error or an end-of-file condition. Use feof or ferror to determine whether an error occurred.
 
למעלה