1
0
mirror of git://projects.qi-hardware.com/gmenu2x.git synced 2024-11-25 15:56:15 +02:00

Make writeStringToFile resilient against short writes

There are various situations in which write() might write less than
the requested amount. In that case, if any progress was made (more
than 0 bytes written), try again, otherwise consider it an error.

Thanks to Nebuleon for reviewing.
This commit is contained in:
Maarten ter Huurne 2014-08-18 22:51:58 +02:00
parent 104d749513
commit e12c896b99

View File

@ -92,7 +92,19 @@ bool writeStringToFile(string const& filename, string const& data) {
} }
// Write temporary file. // Write temporary file.
bool ok = write(fd, data.c_str(), data.size()) >= 0; const char *bytes = data.c_str();
size_t remaining = data.size();
bool ok = true;
while (remaining != 0) {
ssize_t written = write(fd, bytes, remaining);
if (written <= 0) {
ok = false;
break;
} else {
bytes += written;
remaining -= written;
}
}
if (ok) { if (ok) {
ok = fsync(fd) == 0; ok = fsync(fd) == 0;
} }