dja
dja

Reputation: 3

C++ I can't use an fstream variable to save to a file

can anyone recognize mistake of using fstream variable fFile here? because at function Save() writing to disk process (by function WriteTo()) is always fail. But if I declare new local fstream variable instead of fFile, save is ok. (please see part of the code below)

thank you


class CardCollection{
public:
    CardCollection();
    int Open(const char filename[]);    
    void Close();   
    void Close();   
int NumCards()const;    
void ReportStatus()const;   
void AddCards();    
void DeleteCard(int cardnum);   
void ShowCard(int cardnum)const;    
void ChangeCard(int cardnum);   
void DoFind();  
void DoFindAgain(); 
void DoView();
private:
int GetField(int anyallowed);   
void Load();    
int fNumCards;
char *fFileName;    
std::fstream fFile;
DynamicArray fStore;
char *fFindString;
int fFindPos;
int fSearchField;
};



int CardCollection::Open(const char filename[])
{
    //Keep copy of filename
fFileName = new char[strlen(filename)+1];
strcpy(fFileName, filename);

fFile.open(fFileName, std::ios::out | std::ios::in);
if(!fFile.good())
    return -1;
Load();
return 0;
}

void CardCollection::Save()
{
for(int i = fNumCards ; i > 0; i--){
    RefCard *r = (RefCard*) fStore.Nth(i);
    r->WriteTo(fFile);      // If I declare a new fstream here
                    // instead of using fFile, save is ok
}
if(fFile.good()){
    std::cout << "Saving completed";
}
else{
    std::cout << "Saving error";
}
}

Upvotes: 0

Views: 215

Answers (1)

john
john

Reputation: 87959

I'm willing to bet that you don't reset the fstream after you have loaded the data.

Add this to the beginning of Save

fFile.clear();
fFile.seekp(0);

Upvotes: 1

Related Questions