-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfile.c
124 lines (112 loc) · 2.34 KB
/
file.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <stdio.h>
#ifdef HAVE_STDDEF_H
# include <stddef.h>
#else
# ifndef NULL
# define NULL ((void *)0)
# endif
#endif
#ifdef STDC_HEADERS
# include <stdlib.h>
#else
# ifdef HAVE_MALLOC_H
# include <malloc.h>
# endif
#endif
#ifdef HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif
#include "int.h"
#include "file.h"
#include <stdint.h>
/** FIXME: this is not portable and the interface is ugly - rewrite. **/
int f_read(void *outptr, size_t size, size_t nmemb, FILE *stream)
{
unsigned char * tmp;
size_t count;
unsigned int num, pos;
tmp = malloc(size*nmemb);
if (tmp==NULL)
{
fprintf(stderr, "malloc failed\n");
return 0;
}
count = fread(tmp, size, nmemb, stream);
if (count!=nmemb)
fprintf(stderr, "short read\n");
pos = 0;
switch (size)
{
default:
case 1:
for (num=0; num<count; num++)
{
((unsigned char *)outptr)[num] = buff_to_uint8(tmp, &pos);
}
break;
case 2:
for (num=0; num<count; num++)
{
((unsigned short *)outptr)[num] = buff_to_uint16(tmp, &pos);
}
break;
case 4:
for (num=0; num<count; num++)
{
((uint32_t *)outptr)[num] = buff_to_uint32(tmp, &pos);
}
break;
}
free(tmp);
return count;
}
/** FIXME: this is not portable and the interface is ugly - rewrite. **/
int f_write(void *inptr, size_t size, size_t nmemb, FILE *stream)
{
unsigned int num, pos, count;
unsigned char tmp[8];
switch (size)
{
default:
case 1:
count = 0;
for (num=0; num<nmemb; num++)
{
pos = 0;
uint8_to_buff(((unsigned char *)inptr)[num], tmp, &pos);
if (fwrite(tmp, size, 1, stream)!=1)
break;
count ++;
}
break;
break;
case 2:
count = 0;
for (num=0; num<nmemb; num++)
{
pos = 0;
uint16_to_buff(((unsigned short *)inptr)[num], tmp, &pos);
if (fwrite(tmp, size, 1, stream)!=1)
break;
count ++;
}
break;
case 4:
count = 0;
for (num=0; num<nmemb; num++)
{
pos = 0;
uint32_to_buff(((unsigned long *)inptr)[num], tmp, &pos);
if (fwrite(tmp, size, 1, stream)!=1)
break;
count ++;
}
break;
}
if (count!=nmemb)
fprintf(stderr, "short write\n");
return count;
}