fread returns empty result for .src file

13 visualizzazioni (ultimi 30 giorni)
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 Commento
Stephen23
Stephen23 il 4 Lug 2018
Modificato: Stephen23 il 4 Lug 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.

Accedi per commentare.

Risposta accettata

Stephen23
Stephen23 il 4 Lug 2018
Modificato: Stephen23 il 4 Lug 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 Commenti
Dvir Haberman
Dvir Haberman il 4 Lug 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 il 4 Lug 2018
For reasons of interoperability I normally write text files using fprintf.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Environment and Settings in Help Center e File Exchange

Prodotti


Release

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by