示例
下面的示例使用 fgetwc 子例程从文件中读取宽字符代码:
#include <stdio.h>
#include <locale.h>
#include <stdlib.h>
main()
{
wint_t retval;
FILE *fp;
wchar_t *pwcs;
(void)setlocale(LC_ALL, "");
/*
** Open a stream.
*/
fp = fopen("file", "r");
/*
** Error Handling if fopen was not successful.
*/
if(fp == NULL){
/* Error handler */
}else{
/*
** pwcs points to a wide character buffer of BUFSIZ.
*/
while((retval = fgetwc(fp)) != WEOF){
*pwcs++ = (wchar_t)retval;
/* break when buffer is full */
}
}
/* Process the wide characters in the buffer */
}
下面的示例使用 getwchar 子例程从标准输入中读取宽字符:
#include <stdio.h>
#include <locale.h>
#include <stdlib.h>
main()
{
wint_t retval;
FILE *fp;
wchar_t *pwcs;
(void)setlocale(LC_ALL, "");
index = 0;
while((retval = getwchar()) != WEOF){
/* pwcs points to a wide character buffer of BUFSIZ. */
*pwcs++ = (wchar_t)retval;
/* break on buffer full */
}
/* Process the wide characters in the buffer */
}
下面的示例使用 ungetwc 子例程将宽字符压入输入流:
#include <stdio.h>
#include <locale.h>
#include <stdlib.h>
main()
{
wint_t retval;
FILE *fp;
(void)setlocale(LC_ALL, "");
/*
** Open a stream.
*/
fp = fopen("file", "r");
/*
** Error Handling if fopen was not successful.
*/
if(fp == NULL){
/* Error handler */
else{
retval = fgetwc(fp);
if(retval != WEOF){
/*
** Peek at the character and return it to the stream.
*/
retval = ungetwc(retval, fp);
if(retval == EOF){
/* Error on ungetwc */
}
}
}
}
下面的示例使用 fgetws 子例程读取文件,一次读一行:
#include <stdio.h>
#include <locale.h>
#include <stdlib.h>
main()
{
FILE *fp;
wchar_t *pwcs;
(void)setlocale(LC_ALL, "");
/*
** Open a stream.
*/
fp = fopen("file", "r");
/*
** Error Handling if fopen was not successful.
*/
if(fp == NULL){
/* Error handler */
}else{
/* pwcs points to wide character buffer of BUFSIZ. */
while(fgetws(pwcs, BUFSIZ, fp) != (wchar_t *)NULL){
/*
** pwcs contains wide characters with null
** termination.
*/
}
}
}
下面的示例使用 fputwc 子例程将宽字符写入输出流:
#include <stdio.h>
#include <locale.h>
#include <stdlib.h>
main()
{
int index, len;
wint_t retval;
FILE *fp;
wchar_t *pwcs;
(void)setlocale(LC_ALL, "");
/*
** Open a stream.
*/
fp = fopen("file", "w");
/*
** Error Handling if fopen was not successful.
*/
if(fp == NULL){
/* Error handler */
}else{
/* Let len indicate number of wide chars to output.
** pwcs points to a wide character buffer of BUFSIZ.
*/
for(index=0; index < len; index++){
retval = fputwc(*pwcs++, fp);
if(retval == WEOF)
break; /* write error occurred */
/* errno is set to indicate the error. */
}
}
}
下面的示例使用 fputws 子例程将宽字符字符串写入文件:
#include <stdio.h>
#include <locale.h>
#include <stdlib.h>
main()
{
int retval;
FILE *fp;
wchar_t *pwcs;
(void)setlocale(LC_ALL, "");
/*
** Open a stream.
*/
fp = fopen("file", "w");
/*
** Error Handling if fopen was not successful.
*/
if(fp == NULL){
/* Error handler */
}else{
/*
** pwcs points to a wide character string
** to output to fp.
*/
retval = fputws(pwcs, fp);
if(retval == -1){
/* Write error occurred */
/* errno is set to indicate the error */
}
}
}