ANSI, UTF 8 구분 소스 샘플 - bami74/me GitHub Wiki

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

using namespace std;

bool AnalyzeFormatUtf8(char *Text, int dwSize)
{
     char *p;
     bool bFind;
 
     bFind=false;
     for (p=Text;p-Text < dwSize;p++) {
          if ((*p & 0x80) == 0x80) {
              bFind=true;
 
              // 상위 비트가 110이고 다음 문자의 상위 비트가 10이면 UTF8맞음
              // p가 문서 끝을 넘거나 중간에 하나라도 규칙에 맞지 않으면 UTF8이 아님
              if ((*p & 0xe0) == 0xc0) {
                   p++;if (p-Text >= dwSize) return false;
                   if ((*p & 0xc0) != 0x80) return false;
                   continue;
              }
 
              // 상위 비트가 1110일 때는 다음 두 문자의 상위 비트가 10이어야 한다.
              if ((*p & 0xf0) == 0xe0) {
                   p++;if (p-Text >= dwSize) return false;
                   if ((*p & 0xc0) != 0x80) return false;
                   p++;if (p-Text >= dwSize) return false;
                   if ((*p & 0xc0) != 0x80) return false;
                   continue;
              }
 
              // 상위 비트가 11110일 때는 다음 세 문자의 상위 비트가 10이어야 한다.
              if ((*p & 0xf8) == 0xf0) {
                   p++;if (p-Text >= dwSize) return false;
                   if ((*p & 0xc0) != 0x80) return false;
                   p++;if (p-Text >= dwSize) return false;
                   if ((*p & 0xc0) != 0x80) return false;
                   p++;if (p-Text >= dwSize) return false;
                   if ((*p & 0xc0) != 0x80) return false;
                   continue;
              }
 
              // 0x80을 넘었는데 상위 비트가 110, 1110, 11110 중 하나가 아니면
              // UTF-8 문서가 아니다.
              return false;
          }
     }
    
     // 0x80 넘는 값이 하나도 없으면 ANSI로 취급한다.
     if (bFind == false) {
          return false;
     }
 
     // 0x80을 넘는 모든 값이 UTF-8의 조건을 만족하면 UTF-8문서이다.
     return true;
}

int main()
{
    /* declare a file pointer */
    FILE    *infile;
    char    *buffer;
    long    numbytes;
     
    /* open an existing file for reading */
    infile = fopen("utf8.txt", "r");
     
    /* quit if the file does not exist */
    if(infile == NULL)
        return 1;
     
    /* Get the number of bytes */
    fseek(infile, 0L, SEEK_END);
    numbytes = ftell(infile);
     
    /* reset the file position indicator to 
    the beginning of the file */
    fseek(infile, 0L, SEEK_SET);	
     
    /* grab sufficient memory for the 
    buffer to hold the text */
    buffer = (char*)calloc(numbytes, sizeof(char));	
     
    /* memory error */
    if(buffer == NULL)
        return 1;
     
    /* copy all the text into the buffer */
    fread(buffer, sizeof(char), numbytes, infile);
    fclose(infile);
    
    /* confirm we have read the file by
    outputing it to the console */
    bool bb = AnalyzeFormatUtf8(buffer, numbytes);
    printf("%d\n", bb);

    /* free the memory we used for the buffer */
    free(buffer);

   return 0;
}
⚠️ **GitHub.com Fallback** ⚠️