I am getting invalid file identifier error in an input file.
1 次查看(过去 30 天)
显示 更早的评论
fid=fopen('input3.txt','r')
Data=fread(fid) In this line
CharData=char(Data)
fclose(fid)
disp(CharData)
0 个评论
回答(1 个)
Walter Roberson
2018-9-28
filename = 'input3.txt';
[fid, msg] = fopen(filename, 'r');
if fid < 0
error('Could not open file "%s" because "%s"', filename, msg);
end
CharData = fread(fid, '*char');
fclose(fid);
Note: this is not exactly the same as what you had. Your code reads data in as if it were doubles, and uses char() to convert each double to text form, effectively the same as
CharData = char( uint16(Data) );
For example if the input value was 97.432345 then that would be converted to 'a' because character position 97 corresponds to 'a'
The code I provided, on the other hand, reads the input file as if it is already in character form, not as if it is in the form of binary double precision floating point.
The code I provided might recognize UTF-8 multibyte sequences on input and convert them to code points. However, whether it does recognize those or not depends upon your operating system and regional settings. If you want to deliberately recognize UTF-8, then
[fid, msg] = fopen(filename, 'r', 'n', 'UTF8');
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!