How to read any file by using txt ?
4 次查看(过去 30 天)
显示 更早的评论
I have a file which is different than txt file but I would like to read it as txt file. It is like right clicking to the icon and choosing 'open with txt' section. I would like to do in matlab and change some parameters inside the txt file. Thanks
0 个评论
回答(1 个)
Geoff
2012-5-22
The only difference between reading a binary file versus a text file is to translate end-of-line characters. Other than that (and implicitly, the types of characters you get in text versus binary), there's no difference. I would recommend you read the file as binary.
Unless you're saying that it is ACTUALLY a text file but just has a different file extension. Then I would recommend opening in text mode as per usual.
To open in binary mode:
fid = fopen( 'myfile.dat', 'rb' );
allbytes = fread(fid); % this call reads all characters from the file
fclose(fid);
To open in text mode:
fid = fopen('myfile.dat', 'rt' );
line = fgetl(fid); % this call reads a single line from the file
fclose(fid);
Have a look at this:
[EDIT] From your example...
infile = fopen( 'myfile.$PJ', 'rt' );
outfile = fopen( 'myfile_processed.$PJ', 'wt' );
while ~feof(infile)
line = fgetl(infile);
toks = textscan(line, '%s%f', 1);
if ~isempty(toks)
switch toks{1}
case {'HEIGHT', 'HOFFST', 'TOWHT'}
line = sprintf( '%s %d', toks{1}, fix(toks{2}+1) );
end
end
fprintf( outfile, '%s\n', line );
end
fclose(infile);
fclose(outfile);
6 个评论
Geoff
2012-5-31
Oh, I was out by one level of indirection =( The tokens are returned as a cell array, and the string in the first cell is itself a cell... So you need something like:
if ~isempty(toks) && iscell(toks{1})
Then you need to turn all the toks{1} references into toks{1}{1}
You could've worked this out by reading that error message and using the debugger! =P Don't give up and think of crazy alternative solutions just because there is an error in the code. I wrote that code into a web browser as a rough guide for you to follow.
As for reading and writing the same file, I wouldn't recommend it... But yes, you can, and in your case you would have to make sure you are replacing exactly the same number of bytes which may involve replacing some with spaces... The problem comes when you want to insert a number that is longer, and you need to shuffle all the rest of the bytes in the file.... So please don't go and make your problem more complicated than it needs to be. If you don't follow this piece of advice, then run into trouble and ask me to help, you'll be disappointed! =)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!