Main Content

Writing to read-only resource

File initially opened as read only is modified

Description

This defect occurs when you attempt to write to a file that you have opened earlier in read-only mode.

For instance, you open a file using fopen with the access mode argument r. You write to that file with a function in the fprintf family.

Risk

Writing to a read-only file causes undefined behavior.

Fix

If you want to write to the file, open the file in a mode that is suitable for writing.

Examples

expand all

#include <stdio.h>

void func(void) {
    FILE* fp ;

    fp = fopen("file.txt", "r");
    fprintf(fp, "Some data");
    fclose(fp);
}

In this example, the file file.txt is opened in read-only mode. When the FILE pointer associated with file.txt is used as an argument of fprintf, a Writing to read-only resource defect occurs.

Correction — Open File as Writable

One possible correction is to use the access specifier "a" instead of "r". file.txt is now open for output at the end of the file.

#include <stdio.h>

void func(void) {
    FILE* fp ;

    fp = fopen("file.txt", "a");
    fprintf(fp, "Some data");
    fclose(fp);
}

Result Information

Group: Resource management
Language: C | C++
Default: On for handwritten code, off for generated code
Command-Line Syntax: READ_ONLY_RESOURCE_WRITE
Impact: High

Version History

Introduced in R2015b