I am getting invalid file identifier error in an input file.

1 visualizzazione (ultimi 30 giorni)
fid=fopen('input3.txt','r')
Data=fread(fid) In this line
CharData=char(Data)
fclose(fid)
disp(CharData)

Risposte (1)

Walter Roberson
Walter Roberson il 28 Set 2018
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');

Categorie

Scopri di più su Data Type Conversion in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by