fread returns empty result for .src file

6 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2018-7-4
编辑:Stephen23 2018-7-4
"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.

请先登录,再进行评论。

采纳的回答

Stephen23
Stephen23 2018-7-4
编辑:Stephen23 2018-7-4
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 个评论
Dvir Haberman
Dvir Haberman 2018-7-4
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 2018-7-4
For reasons of interoperability I normally write text files using fprintf.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Low-Level File I/O 的更多信息

标签

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by