Problem With read Function
Here is My Code:
Code:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
class Student
{
public:
Student(string name = "", int num = 0, int unit = 0)
{
setName(name);
this->num = num;
this->unit = unit;
}
void set(string name = "", int num = 0, int unit = 0)
{
setName(name);
this->num = num;
this->unit = unit;
}
void setName(string n)
{
int len = n.length();
len = (len < 15) ? len : 14;
n.copy(this->name, len);
name[len] = '\0';
}
char * getName()
{
return name;
}
int getNum()
{
return num;
}
int getUnit()
{
return unit;
}
private:
char name[15];
int num, unit;
};
int main()
{
ofstream o("test.bin", ios::out| ios::binary);
ifstream f("test.bin", ios::in| ios::binary);
Student s;
Student st;
Student stu;
if(!f || !o)
{
cerr << "Error!";
exit(1);
}
string name;
int num, unit;
for(int i = 0;i < 50;i++)
{
o.write(reinterpret_cast<const char *>(&s), sizeof(Student));
}
cin >> name >> num >> unit;
while(num > 0 && num <= 50)
{
st.set(name, num, unit);
o.seekp((st.getNum() - 1) * sizeof(Student));
o.write(reinterpret_cast<const char *>(&st), sizeof(Student));
cin >> name >> num >> unit;
}
f.read(reinterpret_cast<char *>(&stu), sizeof(Student));
while(f.good())
{
if(stu.getNum() != 0 )
{
cout << "Name : " << stu.getName() << endl;
}
f.read(reinterpret_cast<char *>(&stu), sizeof(Student));
}
f.close();
return 0;
}
My Problem is When I Write n Student's information in file, Read Function only read n - 1 information from file! for example if I enter this input:
1 1 1
2 2 2
-1 -1 -1
Output is :
Name : 1
Re: Problem With read Function
Quote:
Originally Posted by
N@R!MAN
My Problem is When I Write n Student's information in file, Read Function only read n - 1 information from file! for example if I enter this input:
1 1 1
2 2 2
-1 -1 -1
Output is :
Name : 1
Which "Output" do you mean? Where is it in your code?
Did you debug your code?
Re: Problem With read Function
Quote:
Which "Output" do you mean? Where is it in your code?
Did you debug your code?
of Course!
after I read information from file :
Code:
if(stu.getNum() != 0 )
{
cout << "Name : " << stu.getName() << endl;
}
Re: Problem With read Function
I used o.flush() after writing process and mu problem is solved now!!! it was not read function problem!
tnx
Re: Problem With read Function
Just as a comment. Why open the same file twice - once as an input stream, and once as an output stream? Why not open the same file just once for both input and output? You then haven't got to remember to flush the contents of the write stream to make the contents available to the read stream?
Code:
fstream io("test.bin", ios:: out | ios:: in | ios:: binary);