ini.cpp
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00012 #include "stdafx.h"
00013 #include "debug.h"
00014 #include "ini_type.h"
00015 #include "string_func.h"
00016 #include "fileio_func.h"
00017
00018 #if (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309L) || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 500)
00019 # define WITH_FDATASYNC
00020 # include <unistd.h>
00021 #endif
00022
00023 #ifdef WIN32
00024 # include <shellapi.h>
00025 # include "core/mem_func.hpp"
00026 #endif
00027
00032 IniFile::IniFile(const char * const *list_group_names) : IniLoadFile(list_group_names)
00033 {
00034 }
00035
00041 bool IniFile::SaveToDisk(const char *filename)
00042 {
00043
00044
00045
00046
00047
00048 char file_new[MAX_PATH];
00049
00050 strecpy(file_new, filename, lastof(file_new));
00051 strecat(file_new, ".new", lastof(file_new));
00052 FILE *f = fopen(file_new, "w");
00053 if (f == NULL) return false;
00054
00055 for (const IniGroup *group = this->group; group != NULL; group = group->next) {
00056 if (group->comment) fputs(group->comment, f);
00057 fprintf(f, "[%s]\n", group->name);
00058 for (const IniItem *item = group->item; item != NULL; item = item->next) {
00059 if (item->comment != NULL) fputs(item->comment, f);
00060
00061
00062 if (strchr(item->name, ' ') != NULL ||
00063 item->name[0] == '[') {
00064 fprintf(f, "\"%s\"", item->name);
00065 } else {
00066 fprintf(f, "%s", item->name);
00067 }
00068
00069 fprintf(f, " = %s\n", item->value == NULL ? "" : item->value);
00070 }
00071 }
00072 if (this->comment) fputs(this->comment, f);
00073
00074
00075
00076
00077
00078
00079
00080 #ifdef WITH_FDATASYNC
00081 int ret = fdatasync(fileno(f));
00082 fclose(f);
00083 if (ret != 0) return false;
00084 #else
00085 fclose(f);
00086 #endif
00087
00088 #if defined(WIN32) || defined(WIN64)
00089
00090 TCHAR tfilename[MAX_PATH + 1], tfile_new[MAX_PATH + 1];
00091 _tcsncpy(tfilename, OTTD2FS(filename), MAX_PATH);
00092 _tcsncpy(tfile_new, OTTD2FS(file_new), MAX_PATH);
00093
00094 tfilename[MAX_PATH - 1] = '\0';
00095 tfile_new[MAX_PATH - 1] = '\0';
00096 tfilename[_tcslen(tfilename) + 1] = '\0';
00097 tfile_new[_tcslen(tfile_new) + 1] = '\0';
00098
00099
00100 SHFILEOPSTRUCT shfopt;
00101 MemSetT(&shfopt, 0);
00102 shfopt.wFunc = FO_MOVE;
00103 shfopt.fFlags = FOF_NOCONFIRMATION | FOF_NOCONFIRMMKDIR | FOF_NOERRORUI | FOF_SILENT;
00104 shfopt.pFrom = tfile_new;
00105 shfopt.pTo = tfilename;
00106 SHFileOperation(&shfopt);
00107 #else
00108 rename(file_new, filename);
00109 #endif
00110
00111 return true;
00112 }
00113
00114 FILE *IniFile::OpenFile(const char *filename, size_t *size)
00115 {
00116
00117
00118 return FioFOpenFile(filename, "rb", DATA_DIR, size);
00119 }
00120
00121 void IniFile::ReportFileError(const char * const pre, const char * const buffer, const char * const post)
00122 {
00123 ShowInfoF("%s%s%s", pre, buffer, post);
00124 }