%% Generate Code to Read a Text File
% This example shows how to generate a standalone C library from MATLAB® code that reads a file from disk using the functions fopen/fread/fclose.
%% About the readfile Function
% The readfile.m function takes a file name (or path) as input and returns a string containing the contents of the file.

type readfile

%
%% Generate the MEX Function for Testing
% Generate a MEX function using the codegen command.

codegen readfile

% Before generating C code, you should first test the MEX function in MATLAB to ensure that it is functionally equivalent to the original MATLAB code and that no run-time errors occur. By default, codegen generates a MEX function named readfile_mex in the current folder. This allows you to test the MATLAB code and MEX function and compare the results.
%
%% Run the MEX Function
% Call the generated MEX function and display the size of the returned string and its first 100 characters.

y = readfile_mex('readfile.m');
size(y)
y(1:100)

%
%% Generate C Code

codegen -config:lib readfile

% Using codegen with the specified -config cfg option produces a standalone C library.
%
%% Inspect the Generated Code
% By default, the code generated for the library is in the folder codegen/lib/readfile/.
% The files are:

dir codegen/lib/readfile/

%
%% Inspect the C Code for the readfile.c Function

type codegen/lib/readfile/readfile.c

% Copyright 2012 The MathWorks, Inc.