c - feof detecting false end of file -
i asked different question earlier, way off base problem i've created new question i'm asking entirely different question.
i have function reads given line in text file (given ac variable). performs read of line , checks if last line in file. if increments value.
the problem it's incremented value when it's not actual end of file. think i'm using feof wrong i've had no luck getting work:
int readin(tincan* incan, int toggle) { int ii, isfinished = 0; char fullname[20]; sprintf(fullname, "label_%d.txt", incan->pid); file* fp; fp = fopen(fullname, "r"); if(fp==null) { printf("error: not open %s\n", fullname); } else { (ii=0; ii < ((incan->ac)-1); ii++) { fscanf(fp, "%*d %*d %*d\n"); /*move through lines without scanning*/ } fscanf(fp,"%d %d %d", &incan->ac, &incan->state, &incan->time); } if (feof(fp) && (toggle == 1)) { printf("file ended"); writelog(incan); isfinished = 1; terminated++; } fclose(fp); return finished; }
sample data requested, text file may use:
1 1 30 2 2 5 3 1 1
fscanf correctly assigns values. on second line, feof returns true , terminated incremented. feof returns true again 3rd line , increments terminated second time.
feof()
not detect if file has ended. detects if last read error due file having ended.
feof()
happens after failed read.
so, first read data , check return value. if read failed use feof()
make sure failed because end-of-file reached (other reasons read fail error of kind (network down, bad sector, printer on fire, ...), detectable ferror()
).
Comments
Post a Comment