Main Content


Read contents of file as text



text = fileread(filename) returns contents of the file filename as a character vector.


text = fileread(filename,Encoding=encoding) opens filename using the encoding specified by encoding.


collapse all

Read a file and search it for text of interest.

First, read the file fileread.m into a character vector.

filetext = fileread('fileread.m');

Then, define the text to search for.

expr = '[^\n]*fileread[^\n]*';

Find and return all lines that contain the text 'fileread'.

matches = regexp(filetext,expr,'match');

Display the first matching line.

function out = fileread(filename,args)

Input Arguments

collapse all

Name of file to read, specified as a character vector or string scalar that includes the file extension. fileread leverages automatic character set detection to determine the file encoding.

On UNIX® systems, if filename begins with '~/' or '~username/', the fileread function expands the path to the current or specified user's home directory, respectively.

Depending on the location of your file, filename can take on one of these forms.

Current folder or folder on the MATLAB® path

Specify the name of the file in filename.

If you open a file with read access and the file is not in the current folder, then fileread searches along the MATLAB search path.

Example: 'sample_file.txt'

Other folders

If the file is not in the current folder or in a folder on the MATLAB path, then specify the full or relative path name in filename.

Example: 'C:\myFolder\myFile.sample_file.txt'

Example: 'myFolder\sample_file.txt'

Remote Location

If the file is stored at a remote location, then filename must contain the full path of the file specified as a uniform resource locator (URL) of the form:


Based on your remote location, scheme_name can be one of the values in this table.

Remote Locationscheme_name
Amazon S3™s3
Windows Azure® Blob Storagewasb, wasbs

If you are using a cloud file system, set environment variables to communicate with the remote file system. For more information, see Work with Remote Data.

Example: 's3://bucketname/path_to_file/sample_file.txt'

Example: 'myFile.dat'

Data Types: char | string

Character encoding scheme associated with the file, specified as "" or a standard character encoding scheme name like one of the values in this table. When you do not specify any encoding or specify encoding as "", the fileread function uses the default MATLAB encoding to read the file.











































Example: Encoding="system" uses the system default encoding.

Extended Capabilities

Version History

Introduced before R2006a

expand all