/
common.c
133 lines (109 loc) · 2.65 KB
1
/*
2
3
4
5
6
TiMidity -- Experimental MIDI to WAVE converter
Copyright (C) 1995 Tuukka Toivonen <toivonen@clinet.fi>
This program is free software; you can redistribute it and/or modify
7
it under the terms of the Perl Artistic License, available in COPYING.
8
9
10
11
12
13
14
common.c
*/
#if HAVE_CONFIG_H
# include <config.h>
#endif
15
16
17
18
19
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
20
#include "SDL.h"
21
22
23
#include "options.h"
#include "common.h"
24
25
26
27
28
29
30
31
32
33
34
#if defined(__WIN32__) || defined(__OS2__)
#define CHAR_DIRSEP '\\'
#define is_dirsep(c) ((c) == '/' || (c) == '\\')
#define is_abspath(p) ((p)[0] == '/' || (p)[0] == '\\' || ((p)[0] && (p)[1] == ':'))
#else /* unix: */
#define CHAR_DIRSEP '/'
#define is_dirsep(c) ((c) == '/')
#define is_abspath(p) ((p)[0] == '/')
#endif
35
36
/* The paths in this list will be tried whenever we're reading a file */
static PathList *pathlist = NULL; /* This is a linked list */
37
38
39
/* This is meant to find and open files for reading */
SDL_RWops *open_file(const char *name)
40
{
41
SDL_RWops *rw;
42
43
44
if (!name || !(*name))
{
45
SNDDBG(("Attempted to open nameless file.\n"));
46
47
48
49
50
return 0;
}
/* First try the given name */
51
52
53
SNDDBG(("Trying to open %s\n", name));
if ((rw = SDL_RWFromFile(name, "rb")))
return rw;
54
55
if (!is_abspath(name))
56
57
58
{
char current_filename[1024];
PathList *plp = pathlist;
59
size_t l;
60
61
62
while (plp) /* Try along the path then */
{
63
64
*current_filename = 0;
l = strlen(plp->path);
65
66
67
if(l)
{
strcpy(current_filename, plp->path);
68
if(!is_dirsep(current_filename[l - 1]))
69
{
70
current_filename[l] = CHAR_DIRSEP;
71
72
current_filename[l + 1] = '\0';
}
73
74
}
strcat(current_filename, name);
75
76
77
78
SNDDBG(("Trying to open %s\n", current_filename));
if ((rw = SDL_RWFromFile(current_filename, "rb")))
return rw;
plp = plp->next;
79
}
80
}
81
82
/* Nothing could be opened. */
83
SNDDBG(("Could not open %s\n", name));
84
85
86
87
88
89
90
return 0;
}
/* This'll allocate memory or die. */
void *safe_malloc(size_t count)
{
void *p;
91
92
p = malloc(count);
93
if (p == NULL) {
94
SNDDBG(("Sorry. Couldn't malloc %d bytes.\n", count));
95
}
96
97
return p;
98
99
100
}
/* This adds a directory to the path list */
101
void add_to_pathlist(const char *s, size_t l)
102
{
103
104
105
106
107
PathList *plp = safe_malloc(sizeof(PathList));
if (plp == NULL)
return;
108
plp->path = safe_malloc(l + 1);
109
110
if (plp->path == NULL)
{
111
free (plp);
112
113
return;
}
114
115
strncpy(plp->path, s, l);
plp->path[l] = 0;
116
117
plp->next = pathlist;
pathlist = plp;
118
}
119
120
121
void free_pathlist(void)
{
122
123
PathList *plp = pathlist;
PathList *next;
124
125
126
127
128
129
130
while (plp)
{
next = plp->next;
free(plp->path);
free(plp);
plp = next;
131
}
132
pathlist = NULL;
133
}