* The URL is only stored if the closed-max-items is not 0 and the file
* exists. */
if (c->state.uri && vb.config.closed_max && vb.files[FILES_CLOSED]) {
- char **lines;
- GString *new;
-
- /* The latest closed URL is written first and the surplus items are
- * removed. */
- lines = util_get_lines(vb.files[FILES_CLOSED]);
- new = g_string_new(c->state.uri);
- g_string_append(new, "\n");
- if (lines) {
- int len, i;
-
- len = g_strv_length(lines);
- for (i = 0; i < len - 1 && i < vb.config.closed_max - 1; i++) {
- g_string_append_printf(new, "%s\n", lines[i]);
- }
- g_strfreev(lines);
- }
- g_file_set_contents(vb.files[FILES_CLOSED], new->str, -1, NULL);
- g_string_free(new, TRUE);
+ util_file_prepend_line(vb.files[FILES_CLOSED], c->state.uri,
+ vb.config.closed_max);
}
gtk_widget_destroy(c->window);
return res;
}
+/**
+ * Prepend a new line to the file and make sure there are not more than
+ * max_lines in the file.
+ *
+ * @file: File to prepend the data
+ * @line: Line to be written as new first line into the file.
+ * The line ending is inserted automatic.
+ * @max_lines Maximum number of lines in file after the operation.
+ */
+void util_file_prepend_line(const char *file, const char *line,
+ unsigned int max_lines)
+{
+ char **lines;
+ GString *new_content;
+
+ g_assert(file);
+ g_assert(line);
+
+ lines = util_get_lines(file);
+ /* Write first the new line into the string and append the new line. */
+ new_content = g_string_new(line);
+ g_string_append(new_content, "\n");
+ if (lines) {
+ int len, i;
+
+ len = g_strv_length(lines);
+ for (i = 0; i < len - 1 && i < max_lines - 1; i++) {
+ g_string_append_printf(new_content, "%s\n", lines[i]);
+ }
+ g_strfreev(lines);
+ }
+ g_file_set_contents(file, new_content->str, -1, NULL);
+ g_string_free(new_content, TRUE);
+}
/**
* Retrieves the first line from file and delete it from file.
char *util_expand(Client *c, const char *src, int expflags);
gboolean util_file_append(const char *file, const char *format, ...);
gboolean util_file_prepend(const char *file, const char *format, ...);
+void util_file_prepend_line(const char *file, const char *line,
+ unsigned int max_lines);
char *util_file_pop_line(const char *file, int *item_count);
char *util_get_config_dir(void);
char *util_get_file_contents(const char *filename, gsize *length);