【问题标题】:Qt c++ QFile writes only last input [duplicate]Qt c ++ QFile仅写入最后一个输入[重复]
【发布时间】:2016-05-25 19:40:25
【问题描述】:

我有一个函数 saveResolvedInfo() 应该将每个解析的 ip 地址从结构 _ResolvedInfo 保存到一个 ip.txt 文件:

void saveResolvedInfo()
{
_ResolvedInfo rf;
QFile file("ip.txt");
file.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream out(&file);

out << rf.country << " " << rf.ip << "/n";
}

好吧,它只写最后解析的IP地址。任何想法我的代码有什么问题?

【问题讨论】:

    标签: qt qfile


    【解决方案1】:

    每次调用都会杀死之前的内容,因此您只能看到最后一个的结果。

    这是因为默认情况下,当您打开 QFile 并指定 QIODevice::WriteOnly 时,现有数据将被破坏,如 in the documentation 所述:

    QIODevice::WriteOnly 设备已打开写入。请注意,此模式意味着截断。

    QIODevice::Truncate 如果可能,设备在打开之前会被截断。设备的所有早期内容都将丢失。

    如果要保留现有文件内容,则必须传递QIODevice::Append 标志。

    QIODevice::Append设备以追加模式打开,所有数据都写入文件末尾。

    file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-13
      • 1970-01-01
      • 1970-01-01
      • 2013-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多