Distinguish between ASCII and Binary

13 views (last 30 days)
Tero
Tero on 5 Nov 2020
Edited: Stephen23 on 5 Nov 2020
What could be an elegant way to distinguish an ASCII file from a Binary one? Specifically, I'm working with STL files that can be both, and I need a solution how to seperate those two
Thanks,
Tero
  1 Comment
Stephen23
Stephen23 on 5 Nov 2020
The elegent way is to read the file format description. Wikipedia gives an outline:
Apparently STL text files must start with the string "solid", whereas STL binary files must NOT start with that string. So to know the difference, you just need to read the first five characters. And testing those five characters is easy in "an elegant way", certainly much faster and more elegant than parsing the entire file.

Sign in to comment.

Accepted Answer

Bruno Luong
Bruno Luong on 5 Nov 2020
I don't know if it's an elegant way but I just test if any charater is > 255
fid = fopen(stlfilename,'rt');
if fid > 0
try
c = textscan(fid,'%s','delimiter','\n');
fclose(fid);
catch ME
message = ME.message;
h = errordlg(message);
waitfor(h);
OK = -2;
return
end
else
OK = -2;
message = 'Cannot open STL file';
h = errordlg(message);
waitfor(h);
return
end
c = c{1};
c(cellfun(@isempty,c)) = [];
if max(cellfun(@max,c)) > 255
% Binary
...
else
% Ascii
...
end
  3 Comments
Bruno Luong
Bruno Luong on 5 Nov 2020
We are talking about STL file, that can be ascii/binary, no any binary file.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by