+
+ // We found the key and the value. We already added it at the top, so ignore this one.
+ if(value && sep[1] == '=' && sep[2] == ' ' && !strcmp(sep + 3, value))
+ continue;
+
+ // We found the key but with a different value, delete it if wanted.
+ found++;
+ if((!value || trim) && found > trim)
+ continue;
+
+ *sep = ' ';
+
+copy:
+ fprintf(fw, "%s\n", buf);
+ }
+
+ if(ferror(fr))
+ error = true;
+
+ fclose(fr);
+
+ if(ferror(fw))
+ error = true;
+
+ if(fclose(fw))
+ error = true;
+
+ // If any error occured during reading or writing, exit.
+ if(error) {
+ unlink(tmpname);
+ return false;
+ }
+
+ // Try to atomically replace the old config file with the new one.
+#ifdef HAVE_MINGW
+ char bakname[PATH_MAX];
+ snprintf(bakname, sizeof(bakname), "%s.bak", filename);
+ if(rename(filename, bakname) || rename(tmpname, filename)) {
+ rename(bakname, filename);
+#else
+ if(rename(tmpname, filename)) {
+#endif
+ return false;
+ } else {
+#ifdef HAVE_MINGW
+ unlink(bakname);
+#endif
+ return true;