fputc_unlocked - Linux


Overview

fputc_unlocked() writes a character to a stream and is intended for use by multi-threaded programs. It is similar to fputc(), but it does not lock the stream; therefore, it is not safe to use from multiple threads simultaneously.

Syntax

int fputc_unlocked(int c, FILE *stream);

Parameters

  • c: Character to be written to the stream.
  • stream: Pointer to a FILE object representing the stream.

Options/Flags

None.

Examples

Write a character to a file

#include <stdio.h>

int main() {
  FILE *fp = fopen("myfile.txt", "w");
  fputc_unlocked('A', fp);
  fclose(fp);
  return 0;
}

Write characters to a pipe

#include <stdio.h>
#include <unistd.h>

int main() {
  int pipefd[2];
  pipe(pipefd);
  pid_t child_pid = fork();
  if (child_pid == 0) {
    // Child process
    close(pipefd[0]);
    fputc_unlocked('A', fdopen(pipefd[1], "w"));
  } else {
    // Parent process
    close(pipefd[1]);
    char c = fgetc(fdopen(pipefd[0], "r"));
    printf("Received character: %c\n", c);
  }
  return 0;
}

Common Issues

  • Thread Safety: fputc_unlocked() is not thread-safe, so it should not be used from multiple threads simultaneously.
  • File Permissions: Ensure that the file or stream you are writing to has the appropriate write permissions.

Integration

fputc_unlocked() can be used with other file-handling functions, such as fopen(), fread(), and fwrite(). It is particularly useful in multi-threaded applications where locking is not desired.

Related Commands

  • fputc(): Similar to fputc_unlocked(), but it locks the stream.
  • fprintf(): Formats and writes data to a stream.
  • fwrite(): Writes data from a buffer to a stream.
  • putchar(): Writes a character to the standard output stream.