forked from makestuff/libfpgalink
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.c
75 lines (69 loc) · 1.97 KB
/
util.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
* Copyright (C) 2009-2012 Chris McClelland
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <makestuff.h>
#ifdef WIN32
#include <Windows.h>
#else
#define _BSD_SOURCE
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h>
/*
* Platform-agnostic millisecond sleep function
*/
DLLEXPORT(void) flSleep(uint32 ms) {
#ifdef WIN32
Sleep(ms);
#else
usleep(1000*ms);
#endif
}
/*
* Allocate a buffer big enough to fit file into, then read the file into it, then write the file
* length to the location pointed to by 'length'. Naturally, responsibility for the allocated
* buffer passes to the caller, and must be freed by a call to flFreeFile().
*/
DLLEXPORT(uint8*) flLoadFile(const char *name, uint32 *length) {
FILE *file;
uint8 *buffer;
size_t fileLen;
size_t returnCode;
file = fopen(name, "rb");
if ( !file ) {
return NULL;
}
fseek(file, 0, SEEK_END);
fileLen = (size_t)ftell(file);
fseek(file, 0, SEEK_SET);
// Allocate enough space for an extra byte just in case the file size is odd
buffer = (uint8 *)malloc(fileLen + 1);
if ( !buffer ) {
fclose(file);
return NULL;
}
returnCode = fread(buffer, 1, fileLen, file);
if ( returnCode == fileLen && length != NULL ) {
*length = (uint32)fileLen;
}
buffer[fileLen] = '\0';
fclose(file);
return buffer;
}
DLLEXPORT(void) flFreeFile(uint8 *buffer) {
free((void*)buffer);
}