0

I have a function saveResolvedInfo() that should save each resolved ip address from structure _ResolvedInfo to an ip.txt file:

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

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

Well, it only writes last resolved ip address. Any ideas whats wrong with my code?

1 Answers1

2

Each call kills the previous content, so you are only seeing the result of the last one.

This happens because by default when you open a QFile specifying QIODevice::WriteOnly the existing data is destroyed, as explained in the documentation:

QIODevice::WriteOnly The device is open for writing. Note that this mode implies Truncate.

QIODevice::Truncate If possible, the device is truncated before it is opened. All earlier contents of the device are lost.

If you want to keep the existing file content, you have to pass the QIODevice::Append flag.

QIODevice::Append The device is opened in append mode so that all data is written to the end of the file.

file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text);
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299