Skip to main content

IAR Embedded Workbench for Arm 9.70.x

CERT-FIO42-C_b

In this section:
Synopsis

Close files when they are no longer needed.

Enabled by default

No

Severity/Certainty

Medium/Low

mediumlow.png
Full description

A call to the fopen() or freopen() function must be matched with a call to fclose() before the lifetime of the last pointer that stores the return value of the call has ended or before normal program termination, whichever occurs first.

Coding standards
CERT FIO42-C

Ensure files are properly closed when they are no longer needed

Code examples

The following code example fails the check and will give a warning:

#define O_RDONLY 00000000
#define S_IRUSR 0000400

int func(const char *filename) {
    int fd = open("a.txt", O_RDONLY, S_IRUSR);
    if (-1 == fd) {
        return -1;
    }
    /* ... */
    return 0;
}

The following code example passes the check and will not give a warning about this issue:

#define O_RDONLY 00000000
#define S_IRUSR 0000400

int func(const char *filename) {
    int fd = open("a.txt", O_RDONLY, S_IRUSR);
    if (-1 == fd) {
        return -1;
    }
    /* ... */
    if (-1 == close(fd)) {
        return -1;
    }
    return 0;
}