cwindows

display of € characters when reading a file


I am trying to display all the contents of a text file but I am having problems a certain character like the € is not displayed well it is displayed like that Ôé¼ but I want it to be displayed like that €

the code of my function:

int FileReadNotWrite2(char name[]){
    FILE *files = NULL;
    files = fopen(name, "r");
    if(files == NULL){
        int answer = MessageBoxW(NULL, L"Impossible to open the file.", L"Error", MB_ICONERROR | MB_OK);
        return -1;
    }else{
        char Carack;
        while ((Carack = fgetc(files)) != EOF){
            printf("%c", Carack);
        }
    }
    printf("\n");
    fclose(files);
    return 0;
}

I tried to do this

setlocale(LC_ALL, "en_US.utf8");

and I expect that all the characters that can be read but that it distorts, that it reads them correctly like that I could read the € and other characters which are not displayed well


Solution

  • I'm revisiting an issue I encountered a long time ago. I now consistently use this method to handle UTF-8 encoding. It requires Windows, but it works reliably with C/C++. I'll provide the corrected source code that delivers the best results.

    #include <stdio.h>
    #include <stdbool.h>
    #include <windows.h>
    
    bool file_read(char name[]){
        FILE *files = NULL;
        files = fopen(name, "r");
        if(files == NULL){
            return false;
        }else{
            char Carack;
            while ((Carack = fgetc(files)) != EOF){
                printf("%c", Carack);
            }
        }
        printf("\n");
        fclose(files);
        return true;
    }
    
    
    
    int main(){
    
        SetConsoleOutputCP(CP_UTF8); // UTF 8 support
    
        file_read("d.txt");
    
    }