How to elegantly open or create new file for reading and writing but not discard existing contents?

5 ビュー (過去 30 日間)
If the file exists, open it for reading and writing, but don't discard existing content; else, create it.
Isn't it a very common use case? Why does fopen not seemingly support this?
Note that I don't want to append. I want to read and overwrite some part of the existing content while keep other parts.

採用された回答

Walter Roberson
Walter Roberson 2021 年 8 月 4 日
fopen with 'a' and close immediately. Then fopen 'r+'
This does rely on no process deleting the file between the time it is fopen 'a' and it is fopen again.
  4 件のコメント
埃博拉酱
埃博拉酱 2021 年 8 月 6 日
Though I'm not satisfied, your answer seems to be the best possible
Walter Roberson
Walter Roberson 2021 年 8 月 6 日

The underlying languages of implementation, C and C++, do not support the mode you are requesting.

The calls that do support that mode, open(), is not part of C, and is instead a POSIX call https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html . That is a problem on Windows systems as Windows no longer supports POSIX.

I have not examined to find out if Windows supports the mode. MacOS and Linux potentially could, but Mathworks would have to specifically rewrite the code to use non-portable functions because it is not an available mode using portable functions.

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

その他の回答 (1 件)

KSSV
KSSV 2021 年 8 月 4 日
Read the documentation of fopen, there are multiple options present.
look for fopen with 'a+'. Also have a look on the function exist.
  4 件のコメント
埃博拉酱
埃博拉酱 2021 年 8 月 4 日
I have read the documentation and found no options that exactly match. That's why I ask here. What I'm expecting is clearly written in the question: If the file exists, open it for reading and writing, but don't discard existing content or append; else, create it.
Walter Roberson
Walter Roberson 2021 年 8 月 4 日
編集済み: Walter Roberson 2021 年 8 月 6 日

MATLAB does not provide that combination of open permissions.

C's fopen() does not support that combination https://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html and it has to instead be done through a C open() call followed by a call to upgrade the resulting file descriptor into a file*

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

カテゴリ

Help Center および File ExchangeCalendar についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by