Read from file error

Mar 11, 2015 at 9:29am
Hey everyone. I;m writing a code that store information from a class to a file and then reads from it. it Write to the file correctly but when it reads from the file it doesn't work as it supposed to.
Here's the code:
#include <fstream>
#include "Media.h"


void writeRecord(Media);
Media readRecord(int);

void main()
{
Media obj1;
Media obj2(125,"You know me","I think i failed :P",6,3,2015);
Media obj3(obj1);
writeRecord(obj1);
writeRecord(obj2);
writeRecord(obj3);
readRecord(125).display();
//obj4.display();
system("pause");
}
void writeRecord(Media obj1)
{
Date j;
j = obj1.getRealeaseDate();
try
{
ofstream file("media.txt",ios::app);
if (file.fail())
throw runtime_error("Error opening file");
file << obj1.getNumber() <<"\t"<< obj1.getTrackTitle() <<"\t"<< obj1.getArtiste() <<"\t"<< j.getDay()<<"\t"<<j.getMonth()<<"\t"<<j.getYear()<< endl;
file.close();
}
catch(runtime_error & err)
{
cerr << err.what();
}
}
Media readRecord(int num)
{
Media M1;
try
{
ifstream file("media.txt",ios::in);
if (file.fail()){
throw runtime_error("Error opening file");
}
int no,day,month,year;string title,artiste;
//cout << no << title << artiste << day << month << year << endl;
while(file >> no >> title >> artiste >> day >> month >> year)
{
cout << no << title << artiste << day << month << year << endl;
if(num == no)
{
M1 = Media(num,title,artiste, day,month,year);
break;
}
}
file.close();

}
catch(runtime_error & err)
{
cerr << err.what();
}
return M1;
}
Mar 11, 2015 at 11:16am
Is your program:
1) Not compiles
    * Is other code compiles correctly, i. e. is your compiler configured properly?
    * If it is, give us error message and corresponding code part.
2) Not running
    * Are you sure that it is not a problem with automatically closing console?
    * How do you run it?
    * Is there any error messages?
3) Gives an error when run
    * Is it system error message or error reported in console?
    * Give us error message and input which leads to error.
4) Not giving correct results
    * Tell what you entered, what you expected, and what you got.
    * Are you sure that results you expected are correct?
Mar 11, 2015 at 6:57pm
Thanks for replying.
Firstly there is no error generated at all, it run correctly up until reading back from the file.

This is what i entered:
Media obj1;//Creates a object with default values(1," "," ",1,1,1)
Media obj2(125,"You know me","I think i failed :P",6,3,2015);//Creates object with set values
Media obj3(obj1);//Creates copy of the first object in a new object

so the file looks like:
1 1 1 1
125 you know me i think i failed 6 3 2015
1 1 1 1

when reading from the file i told it to search for 125 but it keeps outputting the first set of informaton that is in the file i.e 1 1 1 1
Topic archived. No new replies allowed.