I want to read all characters from a file including all spaces, what i am trying is
fileRead = textread('myFile.txt', '%c');
disp('Characters total')
disp(length(fileRead))
But the result is not correct because its only counting all characters except space.
So how do i do that, any help would be appreciated?
I want to read file with spaces.
So the help on textread
(or the better alternative textscan
) isn't super clear on how the %c
format specifier handles whitespace.
If you just use a single %c
, it is going to read one character at a time but in this scenario, whitespace is still going to be treated as a delimiter since it falls between two single-character matches.
What the documentation is referring to about %c
matching whitespace is that if you specify an expected length for the %c
specifier (%<length>c
), then whitespace will be included in the match.
textread('z.txt', '%12c')
% my name is z
If you just want to read in an entire file as a character array, I would just use fread
with the '*char'
data type which is a low-level function for accessing file contents if you don't need to parse them at all.
fid = fopen('z.txt', 'r');
data = fread(fid, '*char').';
disp(numel(data))
If you really want to use textread
, another option is to use the %s
(string) format specifier instead of the character specifier and set the 'Whitespace'
parameter to ''
to not treat spaces as whitespace and therefore a delimeter.
textread('z.txt', '%s', 'whitespace', '')