Effacer les filtres
Effacer les filtres

fread returns empty result for .src file

6 vues (au cours des 30 derniers jours)
Dvir Haberman
Dvir Haberman le 4 Juil 2018
Commenté : Stephen23 le 4 Juil 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 commentaire
Stephen23
Stephen23 le 4 Juil 2018
Modifié(e) : Stephen23 le 4 Juil 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.

Connectez-vous pour commenter.

Réponse acceptée

Stephen23
Stephen23 le 4 Juil 2018
Modifié(e) : Stephen23 le 4 Juil 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 commentaires
Dvir Haberman
Dvir Haberman le 4 Juil 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 le 4 Juil 2018
For reasons of interoperability I normally write text files using fprintf.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Low-Level File I/O dans Help Center et File Exchange

Tags

Produits


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by