필터 지우기
필터 지우기

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

조회 수: 3 (최근 30일)
Axel Wong
Axel Wong 2022년 1월 17일
편집: Stephen23 2022년 1월 17일
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
Axel Wong
Axel Wong 2022년 1월 17일
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 2022년 1월 17일
편집: Stephen23 2022년 1월 17일
@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).

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Low-Level File I/O에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by