File I/O and File System in MATLAB
Table of Contents
- Low-Level File I/O
- File System
Low-Level File I/O
Write a text file with the following MATLAB built-in functions:
💡 Learn more: Export to Text Data Files with Low-Level I/O - MATLAB & Simulink
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.
. .git README.md .. LICENSE
listing = dir('dirpath')- return the folder information in a structure array.
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
💡 Learn more: Check existence of variable, script, function, folder, or class - MATLAB exist
Exclude ' . ' and ' .. ' From Listing Files and Folder
dir() function always returns
.. 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
It will call the
dir(path) function but return the folder information in a struct array without the rows for
List Files and Folders with non-ASCII Characters
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:
jDir(dirpath, 'dir')- list the folder in a specific directory
jDir(dirpath, 'file')- list the files in a specific directory
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.
💡 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: