-
Notifications
You must be signed in to change notification settings - Fork 0
/
readfile.m
81 lines (66 loc) · 2.58 KB
/
readfile.m
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
% y = readfile(filename)
% Read file 'filename' and return a MATLAB string with the contents
% of the file. Internally C functions fopen/fread are used to read
% data from the file.
function y = readfile(filename) %#codegen
% The 'fprintf' function will not be compiled and instead passed
% to the MATLAB runtime. If we choose to generate code for this example,
% all calls to extrinsic functions are automatically eliminated.
coder.extrinsic('fprintf');
% Put class and size constraints on function input.
assert(isa(filename, 'char'));
assert(size(filename, 1) == 1);
assert(size(filename, 2) <= 1024);
% Define a new opaque variable 'f' which will be of type 'FILE *'
% in the generated C code initially with the value NULL.
f = coder.opaque('FILE *', 'NULL');
% Call fopen(filename 'r'), but we need to convert the MATLAB
% string into a C type string (which is the same string with the
% NUL (\0) string terminator).
f = coder.ceval('fopen', c_string(filename), c_string('r'));
% Call fseek(f, 0, SEEK_END) to set file position to the end of
% the file.
coder.ceval('fseek', f, int32(0), coder.opaque('int', 'SEEK_END'));
% We need to initialize the variable 'filelen' to the proper type
% as custom C functions are not analyzed.
filelen = int32(0);
% Call ftell(f) which will return the length of the file in bytes
% (as current file position is at the end of the file).
filelen = coder.ceval('ftell', f);
% Reset current file position
coder.ceval('fseek', f, int32(0), coder.opaque('int', 'SEEK_SET'));
% Initialize a buffer
buffer = zeros(1,65536,'uint8');
% Remaining is the number of bytes to read (from the file)
remaining = filelen;
% Index is the current position to read into the buffer
index = int32(1);
while remaining > 0
% Buffer overflow?
if remaining + index > size(buffer,2)
fprintf('Attempt to read file which is bigger than internal buffer.\n');
fprintf('Current buffer size is %d bytes and file size is %d bytes.\n', size(buffer,2), filelen);
break
end
% Read as much as possible from the file into internal buffer
n = int32(0);
n = coder.ceval('fread', coder.ref(buffer(index)), int32(1), remaining, f);
if n == 0
% Nothing more to read
break;
end
% Did something went wrong when reading?
if n < 0
fprintf('Could not read from file: %d.\n', n);
break;
end
% Update state variables
remaining = remaining - n;
index = index + n;
end
% Close file
coder.ceval('fclose', f);
y = char(buffer(1:index));
% Create a NUL terminated C string given a MATLAB string
function y = c_string(s)
y = [s 0];