1/*
2 * Copyright (c) 2001-2003 Apple Computer, Inc. All Rights Reserved.
3 *
4 * The contents of this file constitute Original Code as defined in and are
5 * subject to the Apple Public Source License Version 1.2 (the 'License').
6 * You may not use this file except in compliance with the License. Please
7 * obtain a copy of the License at http://www.apple.com/publicsource and
8 * read it before using this file.
9 *
10 * This Original Code and all software distributed under the License are
11 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
12 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
13 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
14 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
15 * Please see the License for the specific language governing rights and
16 * limitations under the License.
17 */
18
19/*
20	File:		 cuFileIo.c
21
22	Description: simple file read/write utilities
23*/
24
25#include <unistd.h>
26#include <fcntl.h>
27#include <errno.h>
28#include <stdio.h>
29#include <stdlib.h>
30#include <sys/types.h>
31#include <sys/stat.h>
32#include "cuFileIo.h"
33
34int writeFile(
35	const char			*fileName,
36	const unsigned char	*bytes,
37	unsigned			numBytes)
38{
39	int		rtn;
40	int 	fd;
41
42	fd = open(fileName, O_RDWR | O_CREAT | O_TRUNC, 0600);
43	if(fd < 0) {
44		return errno;
45	}
46	rtn = (int)lseek(fd, 0, SEEK_SET);
47	if(rtn < 0) {
48		return errno;
49	}
50	rtn = (int)write(fd, bytes, (size_t)numBytes);
51	if(rtn != (int)numBytes) {
52		if(rtn >= 0) {
53			printf("writeFile: short write\n");
54		}
55		rtn = EIO;
56	}
57	else {
58		rtn = 0;
59	}
60	close(fd);
61	return rtn;
62}
63
64/*
65 * Read entire file.
66 */
67int readFile(
68	const char		*fileName,
69	unsigned char	**bytes,		// mallocd and returned
70	unsigned		*numBytes)		// returned
71{
72	int rtn;
73	int fd;
74	unsigned char *buf;
75	struct stat	sb;
76	unsigned size;
77
78	*numBytes = 0;
79	*bytes = NULL;
80	fd = open(fileName, O_RDONLY, 0);
81	if(fd < 0) {
82		return errno;
83	}
84	rtn = fstat(fd, &sb);
85	if(rtn) {
86		goto errOut;
87	}
88	size = (unsigned)sb.st_size;
89	buf = malloc(size);
90	if(buf == NULL) {
91		rtn = ENOMEM;
92		goto errOut;
93	}
94	rtn = (int)lseek(fd, 0, SEEK_SET);
95	if(rtn < 0) {
96		goto errOut;
97	}
98	rtn = (int)read(fd, buf, (size_t)size);
99	if(rtn != (int)size) {
100		if(rtn >= 0) {
101			printf("readFile: short read\n");
102		}
103		rtn = EIO;
104	}
105	else {
106		rtn = 0;
107		*bytes = buf;
108		*numBytes = size;
109	}
110errOut:
111	close(fd);
112	return rtn;
113}
114