Difference of using fopen directly vs. using the handle it creates
3 views (last 30 days)
Show older comments
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
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).
Answers (0)
See Also
Categories
Find more on Low-Level File I/O in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!