while(!file.eof) function going infinite

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdio.h>
class a
{
int rollno;
char name[10];
public:
void mod()
{
cout<<"Enter roll no ";cin>>rollno;
cout<<"Enter name ";gets(name);
}
int call()
{
return a;
}
void out()
{
cout<<"Rollno : "<<rollno;
cout<<"\nName : "<<name;
}
};
void main()
{
clrscr(); a x;
fstream file("n.doc",ios::in|ios::out);int pos,n;
cout<<"Enter roll number to be modded ";cin>>n;
while(!file.eof())
{pos=file.tellg();
if(x.call()==n)
{
cout<<"Enter modifications ";x.mod();
file.seekg(pos);
file.write((char*)&x,sizeof(x));
}
}
file.seekg(0);
cout<<"The file now contains ";
while(!file.eof())
{
file.read((char*)&x,sizeof(x));
x.out();
}
file.close();
}


This was a program which I made to modify data in a file called "n.doc".But the eof function is going infinite, and I can't modify anything.Please help!!
Looks like Turbo C++ ?
The code is non-standard in lots of ways, It's hard to give good advice in such a case, other than to use an up-to-date compiler.

As for the code, this is an error, it doesn't compile.
1
2
3
4
int call()
{
     return a;
}


There are two eof loops, I would get rid of both of them. The first has no way to read from the file, it simply does nothing useful.

The second loop, I'd replace with this:
1
2
3
4
while (file.read((char*)&x, sizeof(x)))
{
    x.out();
}
I didn't understand by 'eof does nothing useful'.Please clarify.Yes its Turbo c++.
Last edited on
The first loop looks like this:
1
2
3
4
5
6
7
8
9
10
while (!file.eof())
{
    pos=file.tellg();
    if (x.call()==n)
    {
        cout<<"Enter modifications ";x.mod();
        file.seekg(pos);
        file.write((char*)&x,sizeof(x));
    }
}

The first time around, the file has just been opened, so it is positioned at the start.
At line 3, pos is set to zero.
At line 4, variable x has not been initialised, definitely nothing has been read from the file (no file.read() statement). So the condition (x.call()==n) will be false. So the loop continues from the start. At line 2, pos is set to zero, the if statement is false ... round and round it goes.
Topic archived. No new replies allowed.