What is fwide in C?

The fwide function in C is used to determine whether a stream is byte-oriented or wide-oriented. It may also used to change the orientation of a stream as per the programmer’s requirement.

In order to use the fwide function, the wchar.h library needs to be included in the program, as seen here:

#include <wchar.h> 

Syntax

int fwide( FILE *stream, int mode );

Parameters

The fwide function in C takes in two arguments:

  • stream – The pointer to an input or output stream.
  • mode – Can be 1, 0 or -1. 0 is used to determine the present orientation of a particular stream; 1 is used to set the orientation of a stream to wide-orientation; -1 is used to set it to byte-orientation.

Return value

The fwide function may return a positive number, negative number, or 0. A return value of 0 denotes that the stream passed as the first argument to fwide has no orientation. A value greater than 0 denotes wide-orientation, and a value smaller than 0 denotes byte-orientation.

Example

The code snippet below demonstrates how we may use the fwide function in C to query or reset the orientation of a given stream. In the main function, we first query the orientation of the stdin stream using the fwide function. We pass its return value to the check function, which determines the corresponding orientation with the help of if-else statements and the return value.

Initially, the stdin stream has no orientation as it is a newly opened stream. Subsequently, its orientation is set to byte-orientation as -1 was passed to fwide as its second parameter, as we see here:

#include <wchar.h>
#include <stdio.h>
#include <stdlib.h>
int check(int ret)
{
if (ret > 0)
{
printf("Ret value is %d. The stream is wide oriented!\n",ret);
}
else if(ret < 0)
{
printf("Ret value is %d. The stream is byte oriented!\n",ret);
}
else if (ret == 0)
{
printf("Ret value is %d. The stream has no orientation!\n",ret);
}
}
int main()
{
int ret=fwide(stdin, 0);
check(ret);
//Negative 1 is passed as second argument
ret = fwide(stdin, -1);
check(ret);
}

In this example, the orientation of the stdin stream is reset to wide-orientation as 1 was passed to fwide as its second parameter.

#include <wchar.h>
#include <stdio.h>
#include <stdlib.h>
int check(int ret)
{
if (ret > 0)
{
printf("Ret value is %d. The stream is wide oriented!\n",ret);
}
else if(ret < 0)
{
printf("Ret value is %d. The stream is byte oriented!\n",ret);
}
else if (ret == 0)
{
printf("Ret value is %d. The stream has no orientation!\n",ret);
}
}
int main()
{
int ret = fwide(stdin, 0);
check(ret);
//Positive 1 is passed as second argument
ret = fwide(stdin, 1);
check(ret);
}
Copyright ©2024 Educative, Inc. All rights reserved