C++ <cwchar> - fgetwc() Function
The C++ <cwchar> fgetwc() function returns the wide character currently pointed by the internal file position indicator of the specified stream and advances the position indicator to the next wide character. The multibyte characters of external files are interpreted as wide characters as if wcrtomb() function is called with the stream's internal mbstate_t object.
If the sequence of bytes read cannot be interpreted as a valid wide character, the function returns WEOF and sets errno to EILSEQ.
If a reading error occurs, the function returns WEOF and sets the error indicator for the stream ferror().
If the stream is at end-of-file when the function is called, it returns WEOF and sets end-of-file indicator for the stream feof().
fgetwc() and getwc() are equivalent, except that getwc() may be implemented as a macro in some libraries.
Syntax
wint_t fgetwc (FILE* stream);
Parameters
stream |
Specify a pointer to a FILE object that specifies an input stream. |
Return Value
- On success, the character read is returned.
- If the failure has been caused due to end-of-file condition, returns WEOF and sets the end-of-file indicator for the stream feof().
- If a read error occurs, the function returns WEOF and sets the error indicator for the stream ferror().
- If the sequence of bytes read cannot be interpreted as a valid wide character, the function returns WEOF and sets errno to EILSEQ.
Example:
Lets assume that we have a file called test.txt. This file contains following content:
This is a test file. It contains dummy content.
The below program can be used to read the content of the file using fgetwc() function.
#include <cstdio> #include <cwchar> int main (){ //open the file in read mode FILE *pFile = fopen("test.txt", "r"); //first wide character in the file wint_t wc = fgetwc(pFile); //if first wide character is not WEOF, reads //and writes wide characters from the file //until WEOF is reached while (wc != WEOF) { putwchar(wc); wc = fgetwc(pFile); } //close the file fclose(pFile); return 0; }
The output of the above code will be:
This is a test file. It contains dummy content.
❮ C++ <cwchar> Library