Exemple #1
0
options_t options_init(int argc, char* argv[]) {
	int opt;
	char* dir;

	memset(&options, 0, sizeof(struct struct_options_t));

	if (run_from_src(argv, &dir) != 0) {
		(void) snprintf(options.wwwdir, sizeof(options.wwwdir), "%s/../www", dir);
	} else {
		(void) snprintf(options.wwwdir, sizeof(options.wwwdir), "%s", WWWDIR);
	}
	options.daemonize = 1;
	options.baud = 115200;
	options.port = 8888;
	options.is_tty = 1;
	strncpy(options.tty, "tty", sizeof(options.tty));
	options.mqtt_port = 1883;
	strncpy(options.mqtt_host, "localhost", sizeof(options.mqtt_host));
	strncpy(options.mqtt_name, "dmsrd", sizeof(options.mqtt_name));
	strncpy(options.dnssd_name, "dmsrd", sizeof(options.dnssd_name));
	strncpy(options.stats_database, "/var/lib/dsmrd/dsmrd.stats", sizeof(options.stats_database));

	ini_read("/etc/dsmrd.conf", myfunc, &options);
	ini_read("./dsmrd.conf", myfunc, &options);

	while ((opt = getopt(argc, argv, "cDeol:s:p:tv")) != -1) {
		switch (opt) {
			case 'c':
				options.ignore_crc = 1;
				break;
			case 'D':
				options.daemonize = 0;
				break;
			case 'e':
				options.parity = PARITY_EVEN;
				break;
			case 'o':
				options.parity = PARITY_ODD;
				break;
			case 'l':
				strncpy(options.tty, optarg, sizeof(options.tty));
				break;
			case 's':
				options.baud = atoi(optarg);
				break;
			case 'p':
				options.port = atoi(optarg);
				break;
			case 't':
				options.is_tty = 0;
				break;
			case 'v':
				options.verbose++;
				break;
		}
	}

	return &options;
}
Exemple #2
0
var ini_read_var(STRING *filename, char* section, STRING *entry, var defaultValue)
{
	STRING *tmp = "#64";
	STRING *def = "#64";
	ini_read(tmp, filename, section, entry, str_for_num(def, defaultValue));
	return str_to_num(tmp);
}
Exemple #3
0
float ini_read_float(STRING *filename, char* section, STRING *entry, float defaultValue)
{
	STRING *tmp = "#64";
	STRING *def = "#64";
	ini_read(tmp, filename, section, entry, str_for_float(def, defaultValue));
	return str_to_float(tmp);
}
Exemple #4
0
void initload(void) {

	char	path[MAX_PATH];

	milstr_ncpy(path, file_getcd(inifile), sizeof(path));
	ini_read(path, ini_title, iniitem, INIITEMS);
}
Exemple #5
0
void initload(void) {

	TCHAR	path[MAX_PATH];

	milstr_ncpy(path, file_getcd(inifile), NELEMENTS(path));
	ini_read(path, ini_title, iniitem, NELEMENTS(iniitem));
}
Exemple #6
0
static int cache_flush(TCHAR *buffer, int *size,
                      INI_FILETYPE *rfp, INI_FILETYPE *wfp, INI_FILEPOS *mark)
{
  int terminator_len = (int)_tcslen(INI_LINETERM);
  int pos = 0;

  (void)ini_seek(rfp, mark);
  assert(buffer != NULL);
  buffer[0] = '\0';
  assert(size != NULL);
  assert(*size <= INI_BUFFERSIZE);
  while (pos < *size) {
    (void)ini_read(buffer + pos, INI_BUFFERSIZE - pos, rfp);
    while (pos < *size && buffer[pos] != '\0')
      pos++;            /* cannot use _tcslen() because buffer may not be zero-terminated */
  } /* while */
  if (buffer[0] != '\0') {
    assert(pos > 0 && pos <= INI_BUFFERSIZE);
    if (pos == INI_BUFFERSIZE)
      pos--;
    buffer[pos] = '\0'; /* force zero-termination (may be left unterminated in the above while loop) */
    (void)ini_write(buffer, wfp);
  }
  ini_tell(rfp, mark);  /* update mark */
  *size = 0;
  /* return whether the buffer ended with a line termination */
  return (pos > terminator_len) && (_tcscmp(buffer + pos - terminator_len, INI_LINETERM) == 0);
}
Exemple #7
0
void initload(void) {

	OEMCHAR	path[MAX_PATH];

	initgetfile(path, NELEMENTS(path));
	ini_read(path, ini_title, iniitem, NELEMENTS(iniitem));
}
Exemple #8
0
/**
 * 初期化
 */
void CTraceWnd::Initialize()
{
	WNDCLASS wc;
	ZeroMemory(&wc, sizeof(wc));
	wc.style = CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc = ::DefWindowProc;
	wc.hInstance = GetInstanceHandle();
	wc.hCursor = ::LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = static_cast<HBRUSH>(::GetStockObject(WHITE_BRUSH));
	wc.lpszClassName = s_szClassName;
	if (!::RegisterClass(&wc))
	{
		return;
	}

#if 1
	m_nFlags = 4;
#else
	m_nFlags = 1;
	m_tfh = textfile_create(OEMTEXT("traceout.txt"), 0x800);
#endif

	tracecfg.posx = CW_USEDEFAULT;
	tracecfg.posy = CW_USEDEFAULT;
	tracecfg.width = CW_USEDEFAULT;
	tracecfg.height = CW_USEDEFAULT;
	ini_read(file_getcd(np2trace), inititle, initbl, NELEMENTS(initbl));

	if (!CreateEx(WS_EX_CONTROLPARENT, s_szClassName, s_szTitle, WS_OVERLAPPEDWINDOW, tracecfg.posx, tracecfg.posy, tracecfg.width, tracecfg.height, NULL, NULL))
	{
		return;
	}
	ShowWindow(SW_SHOW);
	UpdateWindow();
}
Exemple #9
0
void initload(void) {

	char	path[MAX_PATH];

	file_cpyname(path, file_getcd(inifile), NELEMENTS(path));
	ini_read(path, ini_title, iniitem, NELEMENTS(iniitem));
}
Exemple #10
0
/**
 * 読み込み
 */
void initload(void)
{
	TCHAR szPath[MAX_PATH];

	initgetfile(szPath, _countof(szPath));
	ini_read(szPath, s_szIniTitle, s_IniItems, _countof(s_IniItems));
}
Exemple #11
0
void cmap_load_file(char *path, char *name, char *ext, void *userdata) {
  cmap_t *cmap = calloc(1, sizeof(cmap_t));

  ini_t *ini = ini_open(path, true, false);
  cmap->description = cstr_copy(ini_read(ini, "info", "description"));
  cmap->author = cstr_copy(ini_read(ini, "info", "author"));
  cmap->version = cstr_copy(ini_read(ini, "info", "version"));

  MAPPING(1, WALKING_FORWARD);
  MAPPING(1, WALKING_BACKWARD);
  MAPPING(1, WALKING_LEFT);
  MAPPING(1, WALKING_RIGHT);
  MAPPING(1, WALKING_ATTACK);
  MAPPING(1, WALKING_ENTER_CAR);
  MAPPING(1, WALKING_JUMP);
  MAPPING(1, WALKING_WEAPON_PREV);
  MAPPING(1, WALKING_WEAPON_NEXT);

  // make all driving keys optional by copying over the walking
  // controls
  cmap_copy_walking2driving(cmap);

  MAPPING(0, DRIVING_FORWARD);
  MAPPING(0, DRIVING_BACKWARD);
  MAPPING(0, DRIVING_LEFT);
  MAPPING(0, DRIVING_RIGHT);
  MAPPING(0, DRIVING_ATTACK);
  MAPPING(0, DRIVING_EXIT_CAR);
  MAPPING(0, DRIVING_HANDBRAKE);
  MAPPING(0, DRIVING_WEAPON_PREV);
  MAPPING(0, DRIVING_WEAPON_NEXT);

  // add all deadzones (fallback is always 0.5)
  DEADZONE_STICK(leftstick);
  DEADZONE_STICK(rightstick);

  ini_cleanup(ini);

  // add it to the list
  cmap_init_t *list = (cmap_init_t *)userdata;
  if (list->first)
    list->last->next = cmap;
  else
    list->first = cmap;
  list->last = cmap;
}
Exemple #12
0
void skbdwin_readini(void) {

	OEMCHAR	path[MAX_PATH];

	skbdcfg.posx = CW_USEDEFAULT;
	skbdcfg.posy = CW_USEDEFAULT;
	initgetfile(path, NELEMENTS(path));
	ini_read(path, skbdapp, skbdini, NELEMENTS(skbdini));
}
Exemple #13
0
void mdbgwin_readini(void) {

	OEMCHAR	path[MAX_PATH];

	mdbgcfg.posx = CW_USEDEFAULT;
	mdbgcfg.posy = CW_USEDEFAULT;
	initgetfile(path, NELEMENTS(path));
	ini_read(path, mdbgapp, mdbgini, NELEMENTS(mdbgini));
}
Exemple #14
0
void
skbdwin_readini(void)
{
	char path[MAX_PATH];

	memset(&skbdcfg, 0, sizeof(skbdcfg));
	file_cpyname(path, modulefile, sizeof(path));
	ini_read(path, ini_title, iniitem, INIITEMS);
}
Exemple #15
0
void kdispwin_readini(void) {

	OEMCHAR	path[MAX_PATH];

	ZeroMemory(&kdispcfg, sizeof(kdispcfg));
	kdispcfg.posx = CW_USEDEFAULT;
	kdispcfg.posy = CW_USEDEFAULT;
	initgetfile(path, NELEMENTS(path));
	ini_read(path, kdispapp, kdispini, NELEMENTS(kdispini));
}
Exemple #16
0
void cmap_map_deadzone_stick(ini_t *ini, char *ini_key, char *ini_section,
                             cmap_deadzone_t *d) {
  if (d->left)
    exit(printf("ERROR: deadzone '%s' has been defined"
                " twice in section '%s'" DOCU,
                ini_key, ini_section));

  // default is always 0.5
  d->left = d->up = d->right = d->down = 0.5 * AXIS_OFFSET_MAX;

  // read the space separated values
  char *value = ini_read(ini, ini_section, ini_key);
  if (!value)
    return;
  cstr_split_t *split = cstr_split(value, ' ', true);

  // factors (left, up, right, down), parsed symmetrically just like
  // in CSS (eg. padding: ...)
  double f[] = {0, 0, 0, 0};
  switch (split->count) {
  case 1:
    f[0] = f[1] = f[2] = f[3] = SPLITVAL2FLOAT(0);
    break;
  case 2:
    f[0] = f[2] = SPLITVAL2FLOAT(0); // left, right
    f[1] = f[3] = SPLITVAL2FLOAT(1); // up, down
    break;
  case 3:
    f[0] = SPLITVAL2FLOAT(0);        // left
    f[1] = f[3] = SPLITVAL2FLOAT(1); // up, down
    f[2] = SPLITVAL2FLOAT(2);        // right
    break;
  case 4:
    f[0] = SPLITVAL2FLOAT(0);
    f[1] = SPLITVAL2FLOAT(1);
    f[2] = SPLITVAL2FLOAT(2);
    f[3] = SPLITVAL2FLOAT(3);
    break;
  default:
    exit(printf("ERROR: invalid value count for '%s':'%s'!"
                " Should be 1...4" DOCU,
                ini_section, ini_key));
  }
  cstr_split_free(split);

  d->left = f[0] * AXIS_OFFSET_MAX;
  d->up = f[1] * AXIS_OFFSET_MAX;
  d->right = f[2] * AXIS_OFFSET_MAX;
  d->down = f[3] * AXIS_OFFSET_MAX;

  // TODO: remove key from ini, so we can verify later that there
  // are no invalid keys
}
void main_menu_actionfunc(tk_t *tk, tk_el_t *el, tk_el_t *el_selected,
                          tk_action_t action) {
  ud_main_t *ud = (ud_main_t *)el->userdata;

  if (action == TK_ACTION_CLEANUP && ud->content->bottom_text_high) {
    free(ud->content->bottom_text_high);
  }

  if (action == TK_ACTION_DRAW_BEFORE_CONTROLS) {
    char *latest_version = chk_latest_version(ud->ui->chk);

    if (ud->content->bottom_text_high)
      free(ud->content->bottom_text_high);

    if (!latest_version || !strcmp(latest_version, G2HR_VERSION)) {
      ud->content->bottom_text_high = NULL;
    } else {
      ud->content->bottom_text_high =
          cstr_merge("UPDATE TO ", latest_version, " AT G2HR.ORG!");
    }
  }

  if (action == TK_ACTION_ENTER) {
    char *exec_after_quit = NULL;

    if (el_selected == ud->poweroff)
      exec_after_quit =
          ini_read(ud->ui->ini_usersettings, "slotmachine", "cmd_shutdown");

    if (el_selected == ud->reboot)
      exec_after_quit =
          ini_read(ud->ui->ini_usersettings, "slotmachine", "cmd_reboot");

    if (exec_after_quit) {
      strncpy(ud->ui->net->exec_after_quit, exec_after_quit,
              G2HR_EXEC_AFTER_QUIT_LEN - 1);
      ud->ui->tk->quit = true;
    }
  }
}
Exemple #18
0
/** ini_browse()
 * \param Callback    a pointer to a function that will be called for every
 *                    setting in the INI file.
 * \param UserData    arbitrary data, which the function passes on the the
 *                    \c Callback function
 * \param Filename    the name and full path of the .ini file to read from
 *
 * \return            1 on success, 0 on failure (INI file not found)
 *
 * \note              The \c Callback function must return 1 to continue
 *                    browsing through the INI file, or 0 to stop. Even when the
 *                    callback stops the browsing, this function will return 1
 *                    (for success).
 */
int  ini_browse(INI_CALLBACK Callback, const void *UserData, const TCHAR *Filename)
{
  TCHAR LocalBuffer[INI_BUFFERSIZE];
  TCHAR *sp, *ep;
  int lenSec, lenKey;
  enum quote_option quotes;
  INI_FILETYPE fp;

  if (Callback == NULL)
    return 0;
  if (!ini_openread(Filename, &fp))
    return 0;

  LocalBuffer[0] = '\0';   /* copy an empty section in the buffer */
  lenSec = _tcslen(LocalBuffer) + 1;
  for ( ;; ) {
    if (!ini_read(LocalBuffer + lenSec, INI_BUFFERSIZE - lenSec, &fp))
      break;
    sp = skipleading(LocalBuffer + lenSec);
    /* ignore empty strings and comments */
    if (*sp == '\0' || *sp == ';' || *sp == '#')
      continue;
    /* see whether we reached a new section */
    ep = _tcschr(sp, ']');
    if (*sp == '[' && ep != NULL) {
      *ep = '\0';
      save_strncpy(LocalBuffer, sp + 1, INI_BUFFERSIZE, QUOTE_NONE);
      lenSec = _tcslen(LocalBuffer) + 1;
      continue;
    } /* if */
    /* not a new section, test for a key/value pair */
    ep = _tcschr(sp, '=');    /* test for the equal sign or colon */
    if (ep == NULL)
      ep = _tcschr(sp, ':');
    if (ep == NULL)
      continue;               /* invalid line, ignore */
    *ep++ = '\0';             /* split the key from the value */
    striptrailing(sp);
    save_strncpy(LocalBuffer + lenSec, sp, INI_BUFFERSIZE - lenSec, QUOTE_NONE);
    lenKey = _tcslen(LocalBuffer + lenSec) + 1;
    /* clean up the value */
    sp = skipleading(ep);
    sp = cleanstring(sp, &quotes);  /* Remove a trailing comment */
    save_strncpy(LocalBuffer + lenSec + lenKey, sp, INI_BUFFERSIZE - lenSec - lenKey, quotes);
    /* call the callback */
    if (!Callback(LocalBuffer, LocalBuffer + lenSec, LocalBuffer + lenSec + lenKey, UserData))
      break;
  } /* for */

  (void)ini_close(&fp);
  return 1;
}
Exemple #19
0
i32_t smart_conf_read(smart_conf_p p_conf, string_t conf_file, i32_t conf_type)
{
	switch (conf_type) {
		case CFT_INI:
			return ini_read(p_conf, conf_file);
			break;
		case CFT_LINE:
			// not support now.
			break;
		default:
			break;
	}

	return F1G_OK;
}
Exemple #20
0
void trace_init(void) {

	HWND	hwnd;

	ZeroMemory(&tracewin, sizeof(tracewin));
	if (!hPrev) {
		WNDCLASS wc;
		wc.style = CS_HREDRAW | CS_VREDRAW;
		wc.lpfnWndProc = traceproc;
		wc.cbClsExtra = 0;
		wc.cbWndExtra = 0;
		wc.hInstance = hInst;
		wc.hIcon = NULL;
		wc.hCursor = LoadCursor(NULL, IDC_ARROW);
		wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
		wc.lpszMenuName = NULL;
		wc.lpszClassName = (LPCTSTR)ClassName;
		if (!RegisterClass(&wc)) {
			return;
		}
	}

#if 1
	tracewin.en = 4;
#else
	tracewin.en = 0;
#endif
	tracewin.fh = FILEH_INVALID;

	tracecfg.posx = CW_USEDEFAULT;
	tracecfg.posy = CW_USEDEFAULT;
	tracecfg.width = CW_USEDEFAULT;
	tracecfg.height = CW_USEDEFAULT;
	ini_read(file_getcd(np2trace), inititle, initbl, 4);

	hwnd = CreateWindowEx(WS_EX_CONTROLPARENT,
							ClassName, ProgTitle,
							WS_OVERLAPPEDWINDOW,
							tracecfg.posx, tracecfg.posy,
							tracecfg.width, tracecfg.height,
							NULL, NULL, hInst, NULL);
	tracewin.hwnd = hwnd;
	if (hwnd == NULL) {
		return;
	}
	ShowWindow(hwnd, SW_SHOW);
	UpdateWindow(hwnd);
}
Exemple #21
0
static
int pce_load_config (ini_sct_t *ini, const char *fname)
{
	if (fname == NULL) {
		return (0);
	}

	pce_log_tag (MSG_INF, "CONFIG:", "file=\"%s\"\n", fname);

	if (ini_read (par_cfg, fname)) {
		pce_log (MSG_ERR, "*** loading config file failed\n");
		return (1);
	}

	return (0);
}
Exemple #22
0
void trace_init(void) {

    HWND	hwnd;

    ZeroMemory(&tracewin, sizeof(tracewin));
    WNDCLASS wc;
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = traceproc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = g_hInstance;
    wc.hIcon = NULL;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = ClassName;
    if (!RegisterClass(&wc)) {
        return;
    }

#if 1
    tracewin.en = 4;
#else
    tracewin.en = 1;
    tracewin.tf = textfile_create(OEMTEXT("traceout.txt"), 0x800);
#endif

    tracecfg.posx = CW_USEDEFAULT;
    tracecfg.posy = CW_USEDEFAULT;
    tracecfg.width = CW_USEDEFAULT;
    tracecfg.height = CW_USEDEFAULT;
    ini_read(file_getcd(np2trace), inititle, initbl, NELEMENTS(initbl));

    hwnd = CreateWindowEx(WS_EX_CONTROLPARENT,
                          ClassName, ProgTitle,
                          WS_OVERLAPPEDWINDOW,
                          tracecfg.posx, tracecfg.posy,
                          tracecfg.width, tracecfg.height,
                          NULL, NULL, g_hInstance, NULL);
    tracewin.hwnd = hwnd;
    if (hwnd == NULL) {
        return;
    }
    ShowWindow(hwnd, SW_SHOW);
    UpdateWindow(hwnd);
}
Exemple #23
0
int LoadGlobals (char *globals_file) 
{
  int retval;
  extern int globals_set;

  if (globals_file!=NULL)
  {
    globals_set = 1;
    ini_read(globals_file);
    globals_set = 0;
    retval=1;
  }
  else
    retval=0;

  return retval;
}
Exemple #24
0
int main(void)
{
	struct ini * ini = ini_new();
	assert(ini != NULL);
	
	FILE * fid = fopen("testfile", "r");
	assert(fid != NULL);
	int res = ini_read(ini, fid);
	fclose(fid);
	
	assert(res == 0);
	
	ini_set(ini, "aa", "pswd", "1234");
	ini_write(ini, stdout);
	ini_del(ini);
	return 0;
}
Exemple #25
0
ini_t *ini_new(const char* filename) {
    ini_t *config = malloc(sizeof(ini_t));
    if (config == NULL) {
        perror("config: malloc");
        return NULL;
    }

    FILE *fp = fopen(filename, "r");
    if (fp == NULL) {
        perror("config: opening file");
        return NULL;
    }

    if (ini_read(fp, config) == -1) {
        return NULL;
    }

    return config;
}
Exemple #26
0
static int cache_flush(TCHAR *buffer, int *size,
                      INI_FILETYPE *rfp, INI_FILETYPE *wfp, INI_FILEPOS *mark)
{
  int pos = 0;

  (void)ini_seek(rfp, mark);
  assert(buffer != NULL);
  buffer[0] = '\0';
  assert(size != NULL);
  while (pos < *size) {
    (void)ini_read(buffer + pos, INI_BUFFERSIZE - pos, rfp);
    pos += _tcslen(buffer + pos);
    assert(pos <= *size);
  } /* while */
  if (buffer[0] != '\0')
    (void)ini_write(buffer, wfp);
  (void)ini_tell(rfp, mark);  /* update mark */
  *size = 0;
  /* return whether the buffer ended with a line termination */
  return (_tcscmp(buffer + pos - _tcslen(INI_LINETERM), INI_LINETERM) == 0);
}
void ui_init_configs(ui_t *ui) {
  // user settings
  ini_t *user = ini_open("data/g2hr.ini", true, false);

  ini_modify(user, "slotmachine", "enabled", "false", false);
  ini_modify(user, "slotmachine", "cmd_shutdown", "poweroff", false);
  ini_modify(user, "slotmachine", "cmd_shutdown", "reboot", false);
  ini_modify(user, "multiplayer", "time", "3 5 10 15 20 25 30", false);

  ini_modify(user, "video", "window_width", "640", false);
  ini_modify(user, "video", "window_height", "480", false);

  // ui settings
  ini_t *settings =
      ini_open(cstr_merge(ui->tk->pref_path, "ui.ini"), false, false);
  ini_modify(settings, "ui", "update_check_enabled", "ask", false);
  ini_modify(settings, "video", "fullscreen", "true", false);
  ini_modify(settings, "video", "menu_upscaling", "linear", false);
  ini_modify(settings, "video", "ingame_lighting", "dusk", false);
  ini_modify(settings, "video", "exploding_scores", "true", false);
  ini_modify(settings, "video", "blood", "true", false);
  ini_modify(settings, "video", "text_speed", "3", false);
  ini_modify(settings, "video", "show_names", "true", false);

  ini_modify(settings, "audio", "3d_sound", "false", false);
  ini_modify(settings, "audio", "music", "5", false);
  ini_modify(settings, "audio", "sfx", "5", false);

  // set values
  ui->multiplayer_time_values =
      cstr_split(ini_read(user, "multiplayer", "time"), ' ', false);
  ui->menu_upscaling_values = cstr_split("nearest linear best", ' ', false);
  ui->ingame_lighting_values = cstr_split("dusk noon random", ' ', false);
  ui->text_speed_values = cstr_split("1 2 3 4 5", ' ', false);

  ui->ini_usersettings = user;
  ui->ini_settings = settings;
}
Exemple #28
0
/** ini_puts()
 * \param Section     the name of the section to write the string in
 * \param Key         the name of the entry to write, or NULL to erase all keys in the section
 * \param Value       a pointer to the buffer the string, or NULL to erase the key
 * \param Filename    the name and full path of the .ini file to write to
 *
 * \return            1 if successful, otherwise 0
 */
int ini_puts(const TCHAR *Section, const TCHAR *Key, const TCHAR *Value, const TCHAR *Filename)
{
  INI_FILETYPE rfp;
  INI_FILETYPE wfp;
  INI_FILEPOS mark;
  TCHAR *sp, *ep;
  TCHAR LocalBuffer[INI_BUFFERSIZE];
  int len, match, flag, cachelen;

  assert(Filename != NULL);
  if (!ini_openread(Filename, &rfp)) {
    /* If the .ini file doesn't exist, make a new file */
    if (Key != NULL && Value != NULL) {
      if (!ini_openwrite(Filename, &wfp))
        return 0;
      writesection(LocalBuffer, Section, &wfp);
      writekey(LocalBuffer, Key, Value, &wfp);
      (void)ini_close(&wfp);
    } /* if */
    return 1;
  } /* if */

  /* If parameters Key and Value are valid (so this is not an "erase" request)
   * and the setting already exists and it already has the correct value, do
   * nothing. This early bail-out avoids rewriting the INI file for no reason.
   */
  if (Key != NULL && Value != NULL) {
    (void)ini_tell(&rfp, &mark);
    match = getkeystring(&rfp, Section, Key, -1, -1, LocalBuffer, sizearray(LocalBuffer));
    if (match && _tcscmp(LocalBuffer,Value) == 0) {
      (void)ini_close(&rfp);
      return 1;
    } /* if */
    /* key not found, or different value -> proceed (but rewind the input file first) */
    (void)ini_seek(&rfp, &mark);
  } /* if */

  /* Get a temporary file name to copy to. Use the existing name, but with
   * the last character set to a '~'.
   */
  ini_tempname(LocalBuffer, Filename, INI_BUFFERSIZE);
  if (!ini_openwrite(LocalBuffer, &wfp)) {
    (void)ini_close(&rfp);
    return 0;
  } /* if */
  (void)ini_tell(&rfp, &mark);
  cachelen = 0;

  /* Move through the file one line at a time until a section is
   * matched or until EOF. Copy to temp file as it is read.
   */
  len = (Section != NULL) ? _tcslen(Section) : 0;
  if (len > 0) {
    do {
      if (!ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) {
        /* Failed to find section, so add one to the end */
        flag = cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
        if (Key!=NULL && Value!=NULL) {
          if (!flag)
            (void)ini_write(INI_LINETERM, &wfp);  /* force a new line behind the last line of the INI file */
          writesection(LocalBuffer, Section, &wfp);
          writekey(LocalBuffer, Key, Value, &wfp);
        } /* if */
        return close_rename(&rfp, &wfp, Filename, LocalBuffer);  /* clean up and rename */
      } /* if */
      /* Copy the line from source to dest, but not if this is the section that
       * we are looking for and this section must be removed
       */
      sp = skipleading(LocalBuffer);
      ep = _tcschr(sp, ']');
      match = (*sp == '[' && ep != NULL && (int)(ep-sp-1) == len && _tcsnicmp(sp + 1,Section,len) == 0);
      if (!match || Key != NULL) {
        if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE)) {
          cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
          (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
          cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE);
        } /* if */
      } /* if */
    } while (!match);
  } /* if */
  cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
  /* when deleting a section, the section head that was just found has not been
   * copied to the output file, but because this line was not "accumulated" in
   * the cache, the position in the input file was reset to the point just
   * before the section; this must now be skipped (again)
   */
  if (Key == NULL) {
    (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
    (void)ini_tell(&rfp, &mark);
  } /* if */

  /* Now that the section has been found, find the entry. Stop searching
   * upon leaving the section's area. Copy the file as it is read
   * and create an entry if one is not found.
   */
  len = (Key!=NULL) ? _tcslen(Key) : 0;
  for( ;; ) {
    if (!ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) {
      /* EOF without an entry so make one */
      flag = cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
      if (Key!=NULL && Value!=NULL) {
        if (!flag)
          (void)ini_write(INI_LINETERM, &wfp);  /* force a new line behind the last line of the INI file */
        writekey(LocalBuffer, Key, Value, &wfp);
      } /* if */
      return close_rename(&rfp, &wfp, Filename, LocalBuffer);  /* clean up and rename */
    } /* if */
    sp = skipleading(LocalBuffer);
    ep = _tcschr(sp, '='); /* Parse out the equal sign */
    if (ep == NULL)
      ep = _tcschr(sp, ':');
    match = (ep != NULL && (int)(skiptrailing(ep,sp)-sp) == len && _tcsnicmp(sp,Key,len) == 0);
    if ((Key != NULL && match) || *sp == '[')
      break;  /* found the key, or found a new section */
    /* copy other keys in the section */
    if (Key == NULL) {
      (void)ini_tell(&rfp, &mark);  /* we are deleting the entire section, so update the read position */
    } else {
      if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE)) {
        cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
        (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
        cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE);
      } /* if */
    } /* if */
  } /* for */
  /* the key was found, or we just dropped on the next section (meaning that it
   * wasn't found); in both cases we need to write the key, but in the latter
   * case, we also need to write the line starting the new section after writing
   * the key
   */
  flag = (*sp == '[');
  cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
  if (Key != NULL && Value != NULL)
    writekey(LocalBuffer, Key, Value, &wfp);
  /* cache_flush() reset the "read pointer" to the start of the line with the
   * previous key or the new section; read it again (because writekey() destroyed
   * the buffer)
   */
  (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
  if (flag) {
    /* the new section heading needs to be copied to the output file */
    cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE);
  } else {
    /* forget the old key line */
    (void)ini_tell(&rfp, &mark);
  } /* if */
  /* Copy the rest of the INI file */
  while (ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) {
    if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE)) {
      cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
      (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
      cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE);
    } /* if */
  } /* while */
  cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
  return close_rename(&rfp, &wfp, Filename, LocalBuffer);  /* clean up and rename */
}
Exemple #29
0
static int getkeystring(INI_FILETYPE *fp, const TCHAR *Section, const TCHAR *Key,
                        int idxSection, int idxKey, TCHAR *Buffer, int BufferSize)
{
  TCHAR *sp, *ep;
  int len, idx;
  enum quote_option quotes;
  TCHAR LocalBuffer[INI_BUFFERSIZE];

  assert(fp != NULL);
  /* Move through file 1 line at a time until a section is matched or EOF. If
   * parameter Section is NULL, only look at keys above the first section. If
   * idxSection is postive, copy the relevant section name.
   */
  len = (Section != NULL) ? _tcslen(Section) : 0;
  if (len > 0 || idxSection >= 0) {
    idx = -1;
    do {
      if (!ini_read(LocalBuffer, INI_BUFFERSIZE, fp))
        return 0;
      sp = skipleading(LocalBuffer);
      ep = _tcschr(sp, ']');
    } while (*sp != '[' || ep == NULL || (((int)(ep-sp-1) != len || _tcsnicmp(sp+1,Section,len) != 0) && ++idx != idxSection));
    if (idxSection >= 0) {
      if (idx == idxSection) {
        assert(ep != NULL);
        assert(*ep == ']');
        *ep = '\0';
        save_strncpy(Buffer, sp + 1, BufferSize, QUOTE_NONE);
        return 1;
      } /* if */
      return 0; /* no more section found */
    } /* if */
  } /* if */

  /* Now that the section has been found, find the entry.
   * Stop searching upon leaving the section's area.
   */
  assert(Key != NULL || idxKey >= 0);
  len = (Key != NULL) ? (int)_tcslen(Key) : 0;
  idx = -1;
  do {
    if (!ini_read(LocalBuffer,INI_BUFFERSIZE,fp) || *(sp = skipleading(LocalBuffer)) == '[')
      return 0;
    sp = skipleading(LocalBuffer);
    ep = _tcschr(sp, '='); /* Parse out the equal sign */
    if (ep == NULL)
      ep = _tcschr(sp, ':');
  } while (*sp == ';' || *sp == '#' || ep == NULL || (((int)(skiptrailing(ep,sp)-sp) != len || _tcsnicmp(sp,Key,len) != 0) && ++idx != idxKey));
  if (idxKey >= 0) {
    if (idx == idxKey) {
      assert(ep != NULL);
      assert(*ep == '=' || *ep == ':');
      *ep = '\0';
      striptrailing(sp);
      save_strncpy(Buffer, sp, BufferSize, QUOTE_NONE);
      return 1;
    } /* if */
    return 0;   /* no more key found (in this section) */
  } /* if */

  /* Copy up to BufferSize chars to buffer */
  assert(ep != NULL);
  assert(*ep == '=' || *ep == ':');
  sp = skipleading(ep + 1);
  sp = cleanstring(sp, &quotes);  /* Remove a trailing comment */
  save_strncpy(Buffer, sp, BufferSize, quotes);
  return 1;
}
static int getkeystring(INI_FILETYPE *fp, const TCHAR *Section, const TCHAR *Key,
                        int idxSection, int idxKey, TCHAR *Buffer, int BufferSize)
{
  TCHAR *sp, *ep;
  int len, idx, isstring;
  enum quote_option quotes;
  TCHAR LocalBuffer[INI_BUFFERSIZE];

  assert(fp != NULL);
  /* Move through file 1 line at a time until a section is matched or EOF. If
   * parameter Section is NULL, only look at keys above the first section. If
   * idxSection is postive, copy the relevant section name.
   */
  len = (Section != NULL) ? _tcslen(Section) : 0;
  if (len > 0 || idxSection >= 0) {
    idx = -1;
    do {
      if (!ini_read(LocalBuffer, INI_BUFFERSIZE, fp))
        return 0;
      sp = skipleading(LocalBuffer);
      ep = _tcschr(sp, ']');
    } while (*sp != '[' || ep == NULL || (((int)(ep-sp-1) != len || _tcsnicmp(sp+1,Section,len) != 0) && ++idx != idxSection));
    if (idxSection >= 0) {
      if (idx == idxSection) {
        assert(ep != NULL);
        assert(*ep == ']');
        *ep = '\0';
        save_strncpy(Buffer, sp + 1, BufferSize, QUOTE_NONE);
        return 1;
      } /* if */
      return 0; /* no more section found */
    } /* if */
  } /* if */

  /* Now that the section has been found, find the entry.
   * Stop searching upon leaving the section's area.
   */
  assert(Key != NULL || idxKey >= 0);
  len = (Key != NULL) ? (int)_tcslen(Key) : 0;
  idx = -1;
  do {
    if (!ini_read(LocalBuffer,INI_BUFFERSIZE,fp) || *(sp = skipleading(LocalBuffer)) == '[')
      return 0;
    sp = skipleading(LocalBuffer);
    ep = _tcschr(sp, '='); /* Parse out the equal sign */
    if (ep == NULL)
      ep = _tcschr(sp, ':');
  } while (*sp == ';' || *sp == '#' || ep == NULL || (((int)(skiptrailing(ep,sp)-sp) != len || _tcsnicmp(sp,Key,len) != 0) && ++idx != idxKey));
  if (idxKey >= 0) {
    if (idx == idxKey) {
      assert(ep != NULL);
      assert(*ep == '=' || *ep == ':');
      *ep = '\0';
      striptrailing(sp);
      save_strncpy(Buffer, sp, BufferSize, QUOTE_NONE);
      return 1;
    } /* if */
    return 0;   /* no more key found (in this section) */
  } /* if */

  /* Copy up to BufferSize chars to buffer */
  assert(ep != NULL);
  assert(*ep == '=' || *ep == ':');
  sp = skipleading(ep + 1);
  /* Remove a trailing comment */
  isstring = 0;
  for (ep = sp; *ep != '\0' && ((*ep != ';' && *ep != '#') || isstring); ep++) {
    if (*ep == '"') {
      if (*(ep + 1) == '"')
        ep++;                 /* skip "" (both quotes) */
      else
        isstring = !isstring; /* single quote, toggle isstring */
    } else if (*ep == '\\' && *(ep + 1) == '"') {
      ep++;                   /* skip \" (both quotes */
    } /* if */
  } /* for */
  assert(ep != NULL && (*ep == '\0' || *ep == ';' || *ep == '#'));
  *ep = '\0';                 /* terminate at a comment */
  striptrailing(sp);
  /* Remove double quotes surrounding a value */
  quotes = QUOTE_NONE;
  if (*sp == '"' && (ep = _tcschr(sp, '\0')) != NULL && *(ep - 1) == '"') {
    sp++;
    *--ep = '\0';
    quotes = QUOTE_DEQUOTE;   /* this is a string, so remove escaped characters */
  } /* if */
  save_strncpy(Buffer, sp, BufferSize, quotes);
  return 1;
}