Krolyxon
Commit 800143a

Branches

Refs →

nsxivutil.c

115 lines · 2.5 KB · C

1/* sxiv: util.c
2 * Copyright (c) 2011 Bert Muennich <muennich at informatik.hu-berlin.de>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17 */
18
19#include <stdlib.h>
20#include <string.h>
21
22#include "options.h"
23#include "util.h"
24
25#define FNAME_LEN 512
26
27void cleanup();
28
29void* s_malloc(size_t size) {
30 void *ptr;
31
32 if (!(ptr = malloc(size)))
33 die("could not allocate memory");
34 return ptr;
35}
36
37void* s_realloc(void *ptr, size_t size) {
38 if (!(ptr = realloc(ptr, size)))
39 die("could not allocate memory");
40 return ptr;
41}
42
43void warn(const char* fmt, ...) {
44 va_list args;
45
46 if (!fmt || options->quiet)
47 return;
48
49 va_start(args, fmt);
50 fprintf(stderr, "sxiv: warning: ");
51 vfprintf(stderr, fmt, args);
52 fprintf(stderr, "\n");
53 va_end(args);
54}
55
56void die(const char* fmt, ...) {
57 va_list args;
58
59 if (!fmt)
60 return;
61
62 va_start(args, fmt);
63 fprintf(stderr, "sxiv: error: ");
64 vfprintf(stderr, fmt, args);
65 fprintf(stderr, "\n");
66 va_end(args);
67
68 cleanup();
69 exit(1);
70}
71
72void size_readable(float *size, const char **unit) {
73 const char *units[] = { "", "K", "M", "G" };
74 int i;
75
76 for (i = 0; i < LEN(units) && *size > 1024; ++i)
77 *size /= 1024;
78 *unit = units[MIN(i, LEN(units) - 1)];
79}
80
81char* readline(FILE *stream) {
82 size_t len;
83 char *buf, *s, *end;
84
85 if (!stream || feof(stream) || ferror(stream))
86 return NULL;
87
88 len = FNAME_LEN;
89 s = buf = (char*) s_malloc(len * sizeof(char));
90
91 do {
92 *s = '\0';
93 fgets(s, len - (s - buf), stream);
94 if ((end = strchr(s, '\n'))) {
95 *end = '\0';
96 } else if (strlen(s) + 1 == len - (s - buf)) {
97 buf = (char*) s_realloc(buf, 2 * len * sizeof(char));
98 s = buf + len - 1;
99 len *= 2;
100 } else {
101 s += strlen(s);
102 }
103 } while (!end && !feof(stream) && !ferror(stream));
104
105 if (ferror(stream)) {
106 s = NULL;
107 } else {
108 s = (char*) s_malloc((strlen(buf) + 1) * sizeof(char));
109 strcpy(s, buf);
110 }
111
112 free(buf);
113
114 return s;
115}