File Exchange

image thumbnail


version 3.0.0 (35.2 KB) by Rik
read any (text) file, either UTF8 or ANSI


Updated 07 Nov 2020

View Version History

GitHub view license on GitHub

If you want to read a (text) file with Matlab, you need to know what encoding it is: UTF-8 (the 'modern' standard) or ANSI (US-ASCII, the 'old' standard). If you have files you want to read automatically, where you don't necessarily know the encoding you would have to guess. This will sometimes result in strange text that you only notice 3 or 4 steps later.

This submission takes care of that problem by providing a single way of reading a file. It preserves leading and trailing spaces, it preserves empty lines, and it can handle both UTF-8 files and ANSI files. Note that although the encoding should be specified in a special leading bit, it is not possible to read this with Matlab. It is therefore possible that a file is read with the wrong encoding, although this should be a very rare occurrence.

It is also possible to enter the file name as a URL. In that case this function will download the file to the temporary directory, read it, and delete it. If that fails, webread/urlread will be used to read the file as a char array, although that may limit which characters can be read depending on the Matlab/Octave release and OS.

Licence: CC by-nc-sa 4.0

Cite As

Rik (2021). readfile (, GitHub. Retrieved .

Comments and Ratings (4)


My main goal was to have a function that works for UTF-8 files and old releases as well. If speed is paramount you should always make sure you know what kind of files you are working with so you can remove input validation and automatic determination. As txt2mat hardly does any processing, I'm not surprised it is faster. It also works on fewer releases.

Since I don't have Matlab on Mac, can you post the result for both functions with timeit?

laurent jalabert

it works on Matlab 2019 on Mac OS High Sierra, but it is super slow compared to txt2mat

omid zandi

thank you very much!! it works great!

zhiwen wan

It works perfectly!!

MATLAB Release Compatibility
Created with R2020b
Compatible with R13SP1 and later releases
Platform Compatibility
Windows macOS Linux
Tags Add Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!