Borrar filtros
Borrar filtros

fread returns empty result for .src file

6 visualizaciones (últimos 30 días)
Dvir Haberman
Dvir Haberman el 4 de Jul. de 2018
Comentada: Stephen23 el 4 de Jul. de 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 comentario
Stephen23
Stephen23 el 4 de Jul. de 2018
Editada: Stephen23 el 4 de Jul. de 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.

Iniciar sesión para comentar.

Respuesta aceptada

Stephen23
Stephen23 el 4 de Jul. de 2018
Editada: Stephen23 el 4 de Jul. de 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 comentarios
Dvir Haberman
Dvir Haberman el 4 de Jul. de 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 el 4 de Jul. de 2018
For reasons of interoperability I normally write text files using fprintf.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Low-Level File I/O en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by