fgetwc - Linux


Overview

fgetwc reads a wide character from a stream. It is most commonly used for reading wide character text files or in applications that process Unicode data.

Syntax

#include <stdio.h>
wint_t fgetwc(FILE *stream);

Parameters:

  • stream: Pointer to the file stream to read from.

Options/Flags

None.

Examples

Example 1: Reading a Wide Character Text File

#include <stdio.h>

int main() {
  FILE *fp = fopen("wide.txt", "r");
  if (fp == NULL) {
    perror("Error opening file");
    return 1;
  }

  wint_t ch;
  while ((ch = fgetwc(fp)) != WEOF) {
    putchar(ch);
  }

  fclose(fp);
  return 0;
}

Example 2: Reading a Wide Character from a String

#include <stdio.h>

int main() {
  wchar_t str[] = L"Wide Character String";

  FILE *fp = fmemopen(str, sizeof(str), "r");
  if (fp == NULL) {
    perror("Error creating stream");
    return 1;
  }

  wint_t ch = fgetwc(fp);
  printf("First character: %lc\n", ch);

  fclose(fp);
  return 0;
}

Common Issues

  • Invalid File Stream: Ensure that the file stream is valid and opened for reading before using fgetwc.
  • Encoding Mismatch: The file may be encoded in a different encoding than what is expected. Check the file encoding before processing.

Integration

fgetwc can be used in conjunction with other file-handling functions, such as fopen, fread, and fwrite. It can also be used to read data from pipes and other non-file sources using fdopen.

Related Commands

  • fscanf: Reads formatted wide character data.
  • fwide: Returns the wide character orientation.
  • wprintf: Prints wide character text to the standard output.