问题描述
我的目标是通过将文件的大小除以文件中的字符数来找到文本文件的编码。但是 fgetc 只读取 UTF8 编码的文件。不适用于 UTF16。请帮助我解决这个问题,或者建议我是否可以替代 fgetc。
#include <stdio.h>
#include <stdlib.h>
void main()
{
findEncode("C:\\UTF-8_TestCase\\TestCase1.txt");
}
int findEncode(char *str){
int ch = NumberOfCharecter(str);
int size = SizeOfFile(str);
if(size/ch == 1){
printf("UTF-8");
}else if(size/ch == 2){
printf("UTF-16");
}else {
printf("UTF-32");
}
}
int NumberOfCharecter(char *str){
FILE *fptr;
char ch;
int character=1;
fptr=fopen(str,"r");
if(fptr==NULL)
{
printf("File does not exist or can not be opened.");
}
while(1)
{
ch = fgetc(fptr); //fgetc only reads UTF8 encoded file. not working for UTF16
if(ch==EOF)
break;
character++;
}
fclose(fptr);
printf("The number of characters in the file %s are : %d\n\n",str,character-1);
return character-1;
}
//SizeOfFile working well
int SizeOfFile(char *str) {
FILE *fptr;
char ch;
int sz;
fptr=fopen(str,"r+");
fseek(fptr,SEEK_END);
sz = ftell(fptr);
printf("the size of the file is %d \n\n",sz);
fclose(fptr);
return sz;
}
解决方法
char ch;
…
ch = fgetc(fptr); //…
if(ch==EOF)
您错误地将 fgetc()
的返回值分配给了 char
;为了将其与 EOF
进行比较,您必须定义 int ch
。在此之后,您会发现 NumberOfCharecter()
返回与 SizeOfFile()
相同的数字,因为 fgetc()
读取的 character 不是字符意义上的字符编码,它与此无关。