简体   繁体   English

写入/读取二进制/文本文件

[英]Writing/reading in to binary/text files

wFile.open(fileName, ios::out | ios::trunc);
if (!(wFile.is_open()))
{
    cout << "Error in opening the file" << endl;
    return false;
}
else
{
    for (unsigned int i = 0; i < Widgets.size(); i++)
    {
        Widgets.at(i)->copyToBinary(fileName);
    }
    wFile.close();
    return true;
}

I'm trying to copy different objects types from a vector. 我正在尝试从矢量复制不同的对象类型。 My problem is that when this code runs for the copy, it only copies the last object. 我的问题是,当此代码为副本运行时,它仅复制最后一个对象。 It seems like the code just overrides the existing text. 似乎代码只是覆盖了现有文本。

Also, I have this code in each class (this is the copyToBinary function): 另外,我在每个类中都有此代码(这是copyToBinary函数):

ofstream file(fName);
file << *this;
file << endl;

What am I missing here? 我在这里想念什么?

You should not reopen the file in copyToBinary . 您不应该在copyToBinary重新打开文件。 Pass wFile as argument not filename : wFile作为参数而不是filename传递:

...copyToBinary(ostream &file) {
  file << *this;
  file << endl;
}

and call ...copyToBinary(wFile) . 并调用...copyToBinary(wFile)

Problem: 问题:

You pass the finename to copyToBinary() , reopening a stream and overwriting it. 您将优良copyToBinary()传递给copyToBinary() ,重新打开流并覆盖它。

Solution: 解:

Pass the wFile stream as reference and write to it without reopening each time 传递wFile流作为参考并写入它,而无需每次都重新打开

void copyToBinary(ostream& file) {
   file << *this;
   file << endl;
}

First, when you are opening the file 首先,当您打开文件时

wFile.open(fileName, ios::out | ios::trunc);

Everytime it is called the existing content get lost as you are using trunc mode. 每当您使用trunc模式时,现有内容都会丢失。 It will be better if you use ios::app mode. 如果使用ios::app模式会更好。 So that whenever the above code runs, it opens the file in append mode. 这样,只要上述代码运行,它就会以附加模式打开文件。

Second, You are passing the filename in the copyToBinary function. 其次,您要在copyToBinary函数中传递文件名。 And By using the default constructor 并且通过使用默认构造函数

ofstream file(fName);

your file is getting opened everytime in default ios::out mode but not in ios::app mode. 您的文件每次都在默认ios::out模式下打开,但不在ios::app模式下打开。 It will be better either you pass the refernece of opened file or open the file in function as append mode. 最好是通过打开文件的引用,或者以附加模式打开文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM