File I/O and File System in MATLAB
Table of Contents
Low-Level File I/O
Write a text file with the following MATLAB built-in functions:
fopen
;fprintf
;fclose
.
💡 Learn more: Export to Text Data Files with Low-Level I/O - MATLAB & Simulink
File System
MATLAB can obtain the information from a file system by the following MATLAB built-in functions:
-
dir
- lists files and folders in the current folder.Example output:
. .git README.md .. LICENSE
-
listing = dir('dirpath')
- return the folder information in a structure array.Example output:
listing = 5x1 struct array with fields: name date bytes isdir datenum
💡 Learn more: - List folder contents - MATLAB dir
-
exist(path,'searchType')
- check existence of variable, script, function, folder, or class.searchType — Type of results to search for
builtin
|class
|dir
|file
|var
💡 Learn more: Check existence of variable, script, function, folder, or class - MATLAB exist
Exclude ' . ' and ' .. ' From Listing Files and Folder
The dir()
function always returns .
and ..
in its result.
.
means the current directory;..
means the parent of the current directory.
They are unnecessary when you solely care about the items inside that directory. You can use the getProjectDir()
function in my matlab-filesystem-io library to replace the built-in dir
function.
e.g. getProjectDir(path)
It will call the dir(path)
function but return the folder information in a struct array without the rows for .
and ..
.
List Files and Folders with non-ASCII Characters
The dir
function does not support internationalization, such as the characters for the Chinese, Japanese, and Korean (CJK) languages. You need to handle non-ASCII characters using the java.io.File Class in MATLAB.
Instead of reinventing the wheel, you can use clone my matlab-filesystem-io library and use the jDir()
function to list the files and folders as below.
-
jDir(dirpath)
- list the files and folders in a specific directory using java.io.File (with supporting Asian characters), return the folder information in a structure array with fields:name
andisDir
.Example output:
-
jDir(dirpath, 'dir')
- list the folder in a specific directoryExample output:
'.git'
-
jDir(dirpath, 'file')
- list the files in a specific directoryExample output:
'LICENSE' 'README.md'
Add Folder(s) to The MATLAB Search Path
When you want MATLAB to use files that locate not in the current working directory, you need to add their file locations to the MATLAB search path using the following functions:
-
addpath(path)
- adds the specified folders to the top of the search path for the current MATLAB session.e.g.
addpath('c:\My Documents\')
💡 Learn more: Add folders to search path - MATLAB addpath
-
addpath(genpath(path))
- add a folder and recursively add its subfolders to the search paths.💡 Learn more: Generate path name - MATLAB genpath
Keep on reading: