fopen always open the file even when it is already open

21 ビュー (過去 30 日間)
Florian Bidaud
Florian Bidaud 2022 年 10 月 19 日
コメント済み: Florian Bidaud 2022 年 10 月 19 日
Hi,
fopen is supposed to return -1 when it can't open the file. So I thought when I had the file open already it would return -1. But when I do it I always have the same output. Have I misunderstood how fopen works ?
I also can't open the file anymore as it gets corrupted if I use 'w' or 'W' option for fopen. I haven't found any explanation to that behaviour.
>> fopen('myFile.xlsx')
ans =
3
>> fclose('all')
ans =
0
% Here I open the file in Excel
>> fopen(myFile)
ans =
3
>> fclose('myFile.xlsx')
ans =
0
Thank you !

採用された回答

Jan
Jan 2022 年 10 月 19 日
編集済み: Jan 2022 年 10 月 19 日
"fopen is supposed to return -1 when it can't open the file" - correct, this is the defined behavior.
"So I thought when I had the file open already it would return -1." - no, this is not the case. See above: If Matlab can open the file, a file handle is replied. You can open a file multiple times for reading.
"Have I misunderstood how fopen works ?" - Yes.
"I also can't open the file anymore as it gets corrupted if I use 'w' or 'W' option for fopen." - correct. 'W' and 'w' open the file for writing. This crops the existing contents of the file. You find this documented in:
doc fopen
The posted code shows the expected behavior.
  1 件のコメント
Florian Bidaud
Florian Bidaud 2022 年 10 月 19 日
Thank you for this answer.
I've read that page already.
I understand that we can open several files for reading, but I've found plenty of topics suggesting using fopen to check if an Excel file was already open, that's why I' m confused.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLow-Level File I/O についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by