C ++我不能使用fstream变量保存到文件

时间:2013-11-29 10:42:31

标签: c++ fstream

有人能识别出在这里使用fstream变量fFile的错误吗?因为在函数Save()写入磁盘进程(通过函数WriteTo())总是失败。 但是如果我声明新的本地fstream变量而不是fFile,则保存就可以了。 (请参阅以下部分代码)

谢谢


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";
}
}

1 个答案:

答案 0 :(得分:1)

我愿意打赌你在加载数据后没有重置fstream

将此添加到保存

的开头
fFile.clear();
fFile.seekp(0);