MATLAB: How to generate C/C++ code from the MATLAB Code which contains file IO commands such as fopen, fclose, and fprintf using MATLAB Coder 2.0 (R2011a)

codefscanfgenerationi/omatlab codernum2strsprintfsscanf

I have a MATLAB function which contains file IO operations such as fopen, fclose, fprintf, etc. I noticed that MATLAB Coder only supports these functions as extrinsic functions that would not get compiled to C/C++ code. Is there a way to generate C/C++ code for my MATLAB code and still be able to do file IO operations?

Best Answer

NOTE: As of R2013a 'fopen', 'fclose' and 'fprintf' are supported for code generation, please navigate to the following link for more information:
For releases prior to R2013a, please refer to the details below:
MATLAB Coder currently does not generate code for file IO functions such as fopen, fclose, and fprintf in release R2011a. Please use the function coder.ceval to call user supplied C/C++ functions in place of these MATLAB file IO functions. For example, one can use coder.ceval to call standard C utilities such as fopen, fclose, and fprintf. In this case, one would need to add a "#include" statement for it to the source code in the header file. This can be achieved by
configuration_object.CustomHeaderCode = '#include <stdio.h>';
Attached please find an example of generating C/C++ code with file IO commands using the MATLAB Coder. The example demonstrates how to write a string and a matrix to a text file using the standard C library utilities, such as "fopen", "fprintf", and "fclose" from the stdio library.
The file to execute in MATLAB is "generate_matlab_coder_file_io_example.m". This file sets up the necessary configurations for code generation and an executable file called file_printing_example.exe will be generated. The MATLAB source file to be built (file_printing_example.m), and all of its MATLAB dependencies are located within the "source_code" folder. When you run the executable file, a text file ('test.txt') will be generated which will contain the text string and the matrix.
MATLAB comments are provided throughout the code to explain the details and the workflow. Please feel free to modify the code to tailor it to your application.