1 /* loadfile.c - loads a file into memory
2 Copyright (C) 1996-2017 Paul Sheer
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
17 02111-1307, USA.
18 */
19
20 #include <config.h>
21 #include <stdlib.h>
22 #include <stdio.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25
26 #ifdef HAVE_FCNTL_H
27 #include <fcntl.h>
28 #endif
29
30 #ifdef HAVE_UNISTD_H
31 #include <unistd.h>
32 #endif
33
34 #include "my_string.h"
35
36 #include "mad.h"
37
38 int readall (int fd, char *buf, int len);
39
40 /*Loads a file into memory */
41 /*Returns the size if the file in filelen and a pointer to the actual file
42 which must be free'd. Returns NULL on error. */
43 /*The returned data is terminated by a null character.*/
loadfile(const char * filename,long * filelen)44 char *loadfile (const char *filename, long *filelen)
45 {
46 long filel;
47 int file;
48 struct stat info;
49 char *data;
50
51 if (!filelen)
52 filelen = &filel;
53
54 if (stat (filename, &info))
55 return NULL;
56
57 if (S_ISDIR (info.st_mode) || S_ISSOCK (info.st_mode)
58 || S_ISFIFO (info.st_mode) || S_ISCHR (info.st_mode)
59 || S_ISBLK (info.st_mode)) {
60 return NULL;
61 }
62 *filelen = info.st_size;
63 if ((data = malloc ((*filelen) + 2)) == NULL)
64 return NULL;
65 if ((file = open (filename, O_RDONLY)) < 0) {
66 free (data);
67 return NULL;
68 }
69 if (readall (file, data, *filelen) < *filelen) {
70 close (file);
71 free (data);
72 return NULL;
73 }
74 data[*filelen] = 0;
75 close (file);
76 return data;
77 }
78
79
savefile(const char * filename,const char * data,int len,int permissions)80 int savefile (const char *filename, const char *data, int len, int permissions)
81 {
82 int file;
83 int count = len;
84 if ((file = creat (filename, permissions)) < 0)
85 return -1;
86 while (count > 0) {
87 int bytes;
88 bytes = write (file, data + (len - count), count);
89 if (bytes == -1) {
90 close (file);
91 return -1;
92 }
93 count -= bytes;
94 }
95 return close (file);
96 }
97
98
99