【问题标题】:fgetc only reads UTF8 encoded file. not working for UTF16fgetc 只读取 UTF8 编码的文件。不适用于 UTF16
【发布时间】:2021-09-15 11:26:47
【问题描述】:

我的目标是通过将文件大小除以文件中的字符数来找到文本文件的编码。但 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, 0, SEEK_END);
    sz = ftell(fptr);
    printf("the size of the file is %d \n\n", sz);
    fclose(fptr);
    return sz;      
}

【问题讨论】:

  • 你怎么知道“文件中的字符数”?你甚至说“字符”这个词是什么意思? Unicode 规范小心地避免了这个词,因为它非常模棱两可。如何区分 UTF16-LE 和 UTF16-BE?如果文件以字节顺序标记 (BOM) 开头,则应该依赖它。
  • 或许fgetwc 会更好?
  • @RolandIllig 请告诉我一种使用 C 查找文件编码的方法
  • @TedLyngmo 不起作用
  • “一种使用 C 查找文件编码的方法”这不存在。您可以根据内容进行猜测,但这只是:猜测。

标签: c utf-8 file-handling utf-16 fgetc


【解决方案1】:
    char ch; 
    …
            ch = fgetc(fptr); //…
              if(ch==EOF)

您错误地将fgetc() 的返回值分配给char;为了将其与EOF 进行比较,您必须定义int ch。在此之后,您会发现NumberOfCharecter() 返回与SizeOfFile() 相同的数字,因为fgetc() 读取的字符 不是编码意义上的字符,它与编码无关.

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-11
相关资源
最近更新 更多