r/C_Programming • u/amadevcode • 5h ago
How to read special characters from a text file?
Hello, I'm doing a little project to improve myself in C. The issue I hit is that non-ASCII characters like 'é' take multiple bytes in UTF-8, so my loop treats them like multiple characters instead of a single one. I don't know how to solve it, can anyone help me with a pretty simple solution because everything that I read online is too complex!
Here is the code if you want to help me:
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
int count_words(FILE *file);
int total_char = 0;
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Format: ./stats file.txt\n");
return 1;
}
FILE *file = fopen(argv[1], "r");
if (file == NULL)
{
printf("Couldn't open the file %s\n", argv[1]);
return 1;
}
int words = count_words(file);
printf("Words: %i\n", words);
fclose(file);
return 0;
}
int count_words(FILE *file)
{
int n = 0;
char character;
bool word = false;
while (fread(&character, 1, 1, file))
{
if (isspace(character) == 0 && ispunct(character) == 0)
{
if (word == false)
n++;
total_char++;
word = true;
}
else
{
word = false;
}
}
return n;
}Thanks for any help!