C++ 我无法使用 fstream 变量保存到文件

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

本文关键字:fstream 变量 存到文件 C++      更新时间:2023-10-16

有人能认出在这里使用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";
}
}

我敢打赌,在加载数据后不会重置fstream

将其添加到Save 的开头

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