ferror_unlocked - Linux


Overview

The ferror_unlocked function in C verifies whether an error has occurred during the last file operation on a stream. It’s typically used in conjunction with other file operations, such as fread or fwrite, to check for potential errors.

Syntax

int ferror_unlocked(FILE *stream);

Parameters

  • stream: A pointer to the FILE structure representing the open stream.

Options/Flags

None.

Examples

Example 1: Verifying an error after reading a file

#include <stdio.h>
#include <stdlib.h>

int main() {
  FILE *fp = fopen("input.txt", "r");
  if (fp == NULL) {
    printf("Error opening file 'input.txt'\n");
    return EXIT_FAILURE;
  }

  char buffer[1024];
  fread(buffer, sizeof(char), 1024, fp);

  if (ferror_unlocked(fp) != 0) {
    printf("An error occurred during reading.\n");
    fclose(fp);
    return EXIT_FAILURE;
  }

  fclose(fp);
  return EXIT_SUCCESS;
}

Example 2: Checking for errors after writing to a file

#include <stdio.h>
#include <stdlib.h>

int main() {
  FILE *fp = fopen("output.txt", "w");
  if (fp == NULL) {
    printf("Error opening file 'output.txt'\n");
    return EXIT_FAILURE;
  }

  fwrite("Hello World", sizeof(char), 11, fp);

  if (ferror_unlocked(fp) != 0) {
    printf("An error occurred during writing.\n");
    fclose(fp);
    return EXIT_FAILURE;
  }

  fclose(fp);
  return EXIT_SUCCESS;
}

Common Issues

  • If ferror_unlocked returns 0, it doesn’t necessarily mean that no error occurred. It only indicates that no error has been detected so far.
  • The error state of a stream can change after performing subsequent file operations.

Integration

ferror_unlocked can be used in conjunction with other C functions such as:

  • fread
  • fwrite
  • fflush
  • strerror

Related Commands

  • perror: Outputs the description of the last error associated with a stream.