メインコンテンツ

MISRA C:2023 Rule 22.4

There shall be no attempt to write to a stream which has been opened as read-only

R2024a 以降

説明

ルール定義

There shall be no attempt to write to a stream which has been opened as read-only 1 .

根拠

標準では、読み取り専用ストリームへの書き込みが試行された場合の動作は指定されていません。

Polyspace 実装

ストリームを読み取り専用で開いた後に、そのストリームで書き込みを行おうとした場合に、Polyspace® はこのルールの違反を報告します。書き込み関数として認識される関数には、以下が含まれます。

  • fprintf(), fprintf_s(), fwprintf(), fwprintf_s(), vfprintf(), vfprintf_s(), vfwprintf(), vfwprintf_s()

  • fwrite()

  • fputc(), fputwc()

  • fputs(), fputws()

  • ungetc(), ungetwc()

違反は、ファイルごとに 1 回報告されます。読み取り専用ファイル ストリームに対する以降の書き込み操作は報告されません。

トラブルシューティング

ルール違反を想定していてもその違反が表示されない場合、コーディング規約違反が想定どおりに表示されない理由の診断を参照します。

すべて展開する

#include <stdio.h>

void func1(void) {
    FILE *fp1 = fopen("tmp.txt", "r");
    (void) fprintf(fp1, "Some text"); /* Non-compliant: Read-only stream */
    (void) fclose(fp1);
}

void func2(void) {
    FILE *fp2 = fopen("tmp.txt", "r+");
    (void) fprintf(fp2, "Some text"); /* Compliant */
    (void) fclose(fp2);
}

この例では、fp1 に関連付けられたファイル ストリームが読み取り専用として開かれています。ストリームへの書き込みがあると、ルール違反になります。

チェック情報

グループ: Resources
カテゴリ: Mandatory
AGC カテゴリ: Mandatory

バージョン履歴

R2024a で導入

すべて展開する


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.