2 * Copyright (C) 2007 Neverball contributors
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or (at your option) any later version.
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 GNU
12 * General Public License for more details.
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
30 /*---------------------------------------------------------------------------*/
32 int read_line(char **dst, FILE *fin)
34 char buffer[MAXSTR] = "";
38 char *store_new = NULL;
45 if (fgets(buffer, sizeof (buffer), fin) == NULL)
56 buffer_size = strlen(buffer) + 1;
58 /* Erase trailing newline. */
60 if (buffer[buffer_size - 2] == '\n')
63 buffer[buffer_size - 2] = '\0';
67 /* Allocate or reallocate space for the buffer. */
69 if ((store_new = (char *) realloc(store, store_size + buffer_size)))
71 /* Avoid passing garbage to string functions. */
77 store_size += buffer_size;
83 fprintf(stderr, "Failed to allocate memory.\n");
90 strncat(store, buffer, buffer_size);
98 char *strip_newline(char *str)
100 char *c = str + strlen(str) - 1;
102 while (c >= str && (*c == '\n' || *c =='\r'))
108 time_t make_time_from_utc(struct tm *tm)
110 struct tm local, *utc;
115 local = *localtime(&t);
118 local.tm_year += local.tm_year - utc->tm_year;
119 local.tm_mon += local.tm_mon - utc->tm_mon ;
120 local.tm_mday += local.tm_mday - utc->tm_mday;
121 local.tm_hour += local.tm_hour - utc->tm_hour;
122 local.tm_min += local.tm_min - utc->tm_min ;
123 local.tm_sec += local.tm_sec - utc->tm_sec ;
125 return mktime(&local);
128 const char *date_to_str(time_t i)
130 static char str[sizeof ("YYYY-mm-dd HH:MM:SS")];
131 strftime(str, sizeof (str), "%Y-%m-%d %H:%M:%S", localtime(&i));
135 int file_exists(const char *name)
139 if ((fp = fopen(name, "r")))
147 int file_rename(const char *src, const char *dst)
150 if (file_exists(dst))
153 return rename(src, dst);
156 void file_copy(FILE *fin, FILE *fout)
161 while ((size = fread(buff, 1, sizeof (buff), fin)) > 0)
162 fwrite(buff, 1, size, fout);
165 char *base_name(const char *name, const char *suffix)
167 static char buf[MAXSTR];
173 /* Remove the directory part. */
175 base = strrchr(name, '/');
179 base = strrchr(name, '\\');
184 if ((tmp = strrchr(base, '\\')))
189 strncpy(buf, base ? base + 1 : name, sizeof (buf));
191 /* Remove the suffix. */
195 int l = strlen(buf) - strlen(suffix);
197 if (l >= 0 && strcmp(buf + l, suffix) == 0)
204 /*---------------------------------------------------------------------------*/