On 8/6/07, Titi Anggono <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I have problem regarding feof(). For example, I have
> two files (data1.txt and data2.txt).
> data1.txt :
> 1 2
>
> data2.txt:
> 1 2
> 1.0 2.0 3.0
> 4.0 5.0 6.0
> 7.0 8.0 9.0
>
> Here is the code that I use to read data1.txt
> ===============
> ...
> while(!feof(fp)){
> fscanf(fp,"%d %d",&n,&m)
> printf("%d %d",n,m);
> }
feof() is only useful for detecting failure after it's happened, not
just before. If you're using feof() in code, it's generally always
wrong. Your code should look like:
while(fscanf(fp,"%d %d",&n,&m) == 2){
printf("%d %d",n,m);
}
if (feof(fp)){ // this is how feof() should be being used...
// was the end of the file
}else{
// problem reading two integers
}
> .....
> ===============
>
> And for the second file
> ===============
> ...
> while(!(feof(fp)){
> fscanf(fp,"%d %d",&n,&m);
> print("%d %d",n,m)
> for(i=0;i<3;i++){
> for(j=0;j<3;j++){
> fscanf(fp,"%lf",a[i][j]);
> }
> }
> }
while(fscanf(fp,"%d %d",&n,&m) == 2){
print("%d %d",n,m)
for(i=0;i<3;i++){
for(j=0;j<3;j++){
if (fscanf(fp,"%lf",a[i][j])) == 1){
// successful read
}else{
// end of file/someone's removed the floppy/data wasn't
a float etc.
if (feof(fp)){
// it really was the end of the file
}else{
// other problem
}
}
}
}
}
[snip]
--
PJH
"I contend that we are both atheists. I just believe in one fewer god
than you do. When you understand why you dismiss all the other
possible gods, you will understand why I dismiss yours."
-- Stephen Roberts