Why writing wchar string to file doesn't work in C

I want my program to take a wchar string from the user and print it to a file,but even though it print the string to the command prompt correctly,when it comes to the file it only prints the ascii characters, any other characters is printed incorrectly.

Example: instead of writing "olá" it prints "ol "

#include <stdio.h>
#include <wchar.h>
#include <locale.h>

int main(){
    FILE *pst = fopen("C:\\teste1.txt","a");
    wchar_t word[100];
    fgetws(word,20,stdin);
    fputws(word,stdout);
    fputws(word,pst);
    fwprintf(pst,word);
    return 0;
}

Upvotes: 0

Views: 140

Answers (1)

gsamaras
gsamaras

Reputation: 73366

The code posted behaves as it should.

Georgioss-MBP:~ gsamaras$ g++ -o m main.cpp 
Georgioss-MBP:~ gsamaras$ ./m
olá
olá
Georgioss-MBP:~ gsamaras$ cat test.txt 
olá
olá

Do that from a terminal, since the problem might be that you are viewing the file from a text editor, whose encoding is not set to display wide characters properly.

Upvotes: 1

Related Questions