fgetws_unlocked - Linux


fgetws_unlocked is a function used to read a line of text from a stream without locking the stream. It’s particularly useful for multithreaded applications where locking the stream for each read operation can cause performance issues.


#include <stdio.h>

wchar_t *fgetws_unlocked(wchar_t * restrict s, int n, FILE * restrict stream);
  • s: Pointer to the buffer where the read line will be stored.
  • n: Maximum number of characters to read, including the terminating null character (\0).
  • stream: Pointer to the stream from which the line will be read.




Simple Usage:

#include <stdio.h>

int main() {
    wchar_t buffer[1024];
    FILE *stream = fopen("input.txt", "r");
    if (stream) {
        fgetws_unlocked(buffer, sizeof(buffer), stream);
        printf("%ws", buffer);
    return 0;

Complex Usage (Reading Lines from Multiple Streams in a Loop):

#include <stdio.h>
#include <pthread.h>

void *read_stream(void *arg) {
    FILE *stream = (FILE *)arg;
    wchar_t buffer[1024];
    while (fgetws_unlocked(buffer, sizeof(buffer), stream)) {
        // Process the line
    return NULL;

int main() {
    pthread_t thread1, thread2;
    FILE *stream1 = fopen("input1.txt", "r");
    FILE *stream2 = fopen("input2.txt", "r");
    if (stream1 && stream2) {
        pthread_create(&thread1, NULL, read_stream, stream1);
        pthread_create(&thread2, NULL, read_stream, stream2);
        pthread_join(thread1, NULL);
        pthread_join(thread2, NULL);
    return 0;

Common Issues

  • Ensure that the buffer provided is large enough to hold the entire line.
  • Check the return value to determine if the end of file was reached or an error occurred.
  • Be cautious when using fgetws_unlocked in multithreaded environments, as the stream is not locked during the read operation.


fgetws_unlocked can be used in conjunction with other functions for advanced tasks, such as:

  • getline: For reading lines of characters from a stream without the need to specify a buffer size.
  • fgets: For reading lines of characters from a stream with locking.

Related Commands

  • fgets
  • getline
  • scanf