Difference of using fopen directly vs. using the handle it creates

3 views (last 30 days)
Hey. What is the difference of the following two usages:
1.
fileName = fopen('myFile.bin','a');
fwrite(fileName,data);
2.
fwrite(fopen('myFile.bin','a'),data);
Would the second end up being more expensive, especially when I have to append to 'data' multiple times? I omitted 'fclose' in both cases above because I would close the file only once, so I guess there should't be too much of a difference in terms of computational cost in between
fclose(fileName)
and
fclose(fopen('myFile.bin','a'))
if this is only ran once.
The reason I couldn't just use case 1 above but have to use case 2 is that there will be multiple files that I will be saving to. It is much easier to just distinguish them with their file names (strings, like "myFile.bin") rather than creating different variable names (like "fileName"). However, if there are other better workaround I would be happy to learn as well!!
Thanks!
  3 Comments
Axel Wong
Axel Wong on 17 Jan 2022
Thanks for your comment. Pretty helpful.
I forgot about testing myself so I just performed the test, and this is the error I got:
Too many open files. Close files to prevent MATLAB instability.
I had previously been testing when the fopen's are only being called <100 times and that was fine, but now I created large data sets (involving calling fopen thousands of times) and I got the above error. So it seems my question is moot because such an approach can't be scaled up. I ended up using the second part of your suggestion and just storing the file handles in a variable.
Stephen23
Stephen23 on 17 Jan 2022
Edited: Stephen23 on 17 Jan 2022
@Axel Wong: if you keep calling FOPEN without FCLOSE then you will reach the OS's limit on how many file handles it can support (note: it is possible to have multiple file handles to the same file):
All things considered, the most robust approach is probably to call FOPEN once per file and allocate its output to an array (could be a structure). Then you can use that array to import/export your data and finally FCLOSE the files (in a loop).

Sign in to comment.

Answers (0)

Community Treasure Hunt

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

Start Hunting!