Как посчитать количество символов в тексте?
Пробовал 2 варианта, через размер файла(fseek), и через цикл while(fgetc(file) != EOF. С файлом с английскими словами возвращает все правильно. С русскими же в 2 раза больше. Можно ли как нибудь сделать, чтобы независимо от языка он возвращал верное кол во символов?
Ответы (1 шт):
Автор решения: AlexGlebe
→ Ссылка
Читайте UTF-8 символы с помощью fgetwc. Работает только с указанной локалью.
NAME
fgetwc, getwc - read a wide character from a FILE stream
SYNOPSIS
#include <stdio.h>
#include <wchar.h>
wint_t fgetwc(FILE *stream);
wint_t getwc(FILE *stream);
DESCRIPTION
The fgetwc() function is the wide-character equivalent of
the fgetc(3) function. It reads a wide character
from stream and returns it. If the end of stream is reached,
or if ferror(stream) becomes true, it returns
WEOF. If a wide-character conversion error occurs, it sets
errno to EILSEQ and returns WEOF.
getwc.c
#include <stdio.h>
#include <wchar.h>
#include <errno.h>
#include <locale.h>
int main(){
setlocale(LC_ALL,"");
FILE * const f = fopen("test","r");
do{
errno=0;
wint_t const wc = fgetwc(f);
if (wc == WEOF) {
if(errno)
printf("error\n");
else
printf("eof\n");
break;}
printf("wc=%d\n",wc);
} while (1);
fclose(f);
}