0

I'm studying C and now I started to see how to manipulate files, that is: how to write data, read and delete it.

However I am experiencing a problem, my program will use accents and special characters, so I set setlocation with my language so that they work perfectly.

But it ends up creating two inconsistencies:

When I put words with accents to save in the file, and I try to display them on the screen, returns several strange characters. Note that accented words within the printf are displayed normally.

enter image description here

When I remove setlocation, the accented words inserted in the file are displayed perfectly, but the printf with accents is not displayed.

enter image description here

My code:

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

int main() {

    setlocale(LC_ALL, "Portuguese");

    FILE *my_file;

    char name[90];

    fopen_s(&my_file, "names.txt", "a");

    printf("Digite uma palavra acentuada [não/ação/maldição]: ");

    scanf_s("%[^\n]", name, 90);

    fputs(name, my_file);
    fputs("\n", my_file);
    fclose(my_file);

    fopen_s(&my_file, "names.txt", "r");

    int i;
    char *result;
    char lines[100];

    i = 1;
    while (!feof(my_file))
    {
        result = fgets(lines, 100, my_file);
        if (result)
            printf("%s", lines);
        i++;
    }

    fclose(my_file);
    return 0;
}

Any suggestions on how to fix this? Thank you.

Bebeto Alves
  • 105
  • 5
  • Well, I can't read Portuguese, but maybe this site post might help you out: https://pt.stackoverflow.com/questions/112263/como-resolver-problemas-de-acentuação-ao-usar-a-função-setlocale – gi097 Oct 31 '18 at 13:22
  • 1
    Read http://utf8everywhere.org/ and consider using `setlocale(LC_ALL, "pt_PT.UTF-8")` – Basile Starynkevitch Oct 31 '18 at 13:38
  • @Yunnosch I don't think this relates to naming of files, the file is called `"names.txt"` which seems to comply with your ideals. :) – unwind Oct 31 '18 at 13:54
  • regarding: ` while (!feof(my_file))` read: [while (!feof(my_file)) always wrong](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong/26557243) – user3629249 Oct 31 '18 at 16:14
  • the language 'Portuguese' uses wide (multibyte) characters. so 1) include the file 'wchar.h' 2) use the correct function calls for wide characters – user3629249 Oct 31 '18 at 16:17

0 Answers0