Filter löschen
Filter löschen

fread returns empty result for .src file

6 Ansichten (letzte 30 Tage)
Dvir Haberman
Dvir Haberman am 4 Jul. 2018
Kommentiert: Stephen23 am 4 Jul. 2018
Hello,
My goal is to read and then edit an .src file such that I can identify and then discard certain lines (i.e. lines 20 to 200).
I try to run the following code:
fileid=fopen('mysrcfile.src', 'w');
read_data=fread(fileid);
yet read_data is always empty. What am I doing wrong?
Help with next steps towards the goal will also be appriciated.
Thanks.
  1 Kommentar
Stephen23
Stephen23 am 4 Jul. 2018
Bearbeitet: Stephen23 am 4 Jul. 2018
"My goal is to read and then edit an .src file such that I can identify and then discard certain lines (i.e. lines 20 to 200)."
It is not clear from your question, but if you are trying to edit the file data itself then I recommend that you do some reading about changing file contents in situ. It is not as trivial as beginners think:
Much easier is to read the whole file into MATLAB memory, make any required changes, then write the file anew.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Stephen23
Stephen23 am 4 Jul. 2018
Bearbeitet: Stephen23 am 4 Jul. 2018
fileid=fopen('mysrcfile.src', 'w');
^ This opens a file in WRITE mode!
WRITE mode clears the file contents!
The fopen help clearly describes the 'w' option with "Open or create new file for writing. Discard existing contents, if any." And that is exactly what you are doing, opening the file (discarding any contents) and then looking to see what contents it has (none, because you just discarded them).
Perhaps you meant to use r+ ?
Personally I would make these two separate operations:
[fid,msg] = fopen(...,'rt') % read!
assert(fid>=3,msg)
... read the old file data here
fclose(fid)
Process the file data here... and then
[fid,msg] = fopen(...,'wt') % write!
assert(fid>=3,msg)
... write the new file data here
fclose(fid)
This makes the intent totally unambiguous just from reading the code.
  2 Kommentare
Dvir Haberman
Dvir Haberman am 4 Jul. 2018
Thank you, this solved the problem. I will take the advice of splitting the r/w actions. Which command would you use to write the file?
Stephen23
Stephen23 am 4 Jul. 2018
For reasons of interoperability I normally write text files using fprintf.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Low-Level File I/O finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by