r/C_Programming • u/amadevcode • 4h 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!
7
Upvotes
14
u/Dazzling_Music_2411 4h ago
Well, yeah, if you want to process UTF-8 characters, you have to use UTF-8 routines.
It would be incredibly difficult - nay, madness - to try and process them as ASCII characters if you don't have to. Find out what Unicode support your environment provides.
4
u/hgs3 3h ago
There's more to text processing than UTF-8. Word boundaries are locale-specific and some languages, like Japanese, don't even use space characters to separate words (you use a dictionary or morphological/ML segmentation).
Since you're still learning, I'd recommend you keep things simple by restricting your program's accepted inputs to ASCII. You can do this by error'ing if you read a byte above 0x7F. Watch out for the signedness of
char! Depending on the C compilercharcan be signed or unsigned. I'd recommend declaring it explicitly asunsigned charto avoid portability pitfalls.3
u/Rararror 4h ago
Study this:
https://datatracker.ietf.org/doc/html/rfc3629
Very well done document and very good programming practice.
1
u/dawalballs 4h ago
Ok, Iām a bit fuzzy on the specifics, but I remember needing to use getwchar if you wanna look that up.
You end up needing to set a locale first and then it should handle things ok. Hopefully this at least sets you on the right path, but someone else will almost certainly give you a better answer than this if you give it a sec
1
u/Ma3dhr0s_ 4h ago
First, I'd recommend using fgetc over fread if you are reading a single character at a time. It is a bit simpler. To handle these weird characters, you might want to have a read on this unicode page. https://en.wikipedia.org/wiki/UTF-8
Check the description heading and you will see a small table. For non-ASCII characters, they are 2, 3 or 4 bytes respectively and have a special value for byte 1, e.g. 2 byte unicode will have 110xxxxx 10xxxxxx as its first 2 bytes, where x is some random bit. To handle these special unicode characters, you will have to do some bitwise stuff to check whether your extracted character has the same "start" as 110xxxxx for checking for 2 byte encoding for example.
Once you recognise the unicode codepoint length, you will have to "skip" over some characters. For example, if you recognise that your character has a start 110xxxxx, you know the next character is the 2nd part of the unicode, 10xxxxxx. What you can do is then just fgetc 1 time here to "skip" the 2nd byte so it doesnt add to your counter. You can also look into fseek, which allows you to jump around where you are reading in the file.
Let me know if you have any questions!
1
u/PseudoFrequency 4h ago edited 4h ago
Basically.... Convert to wide string, may be 16 or 32 bit depending on the platform. On Windows you can use MultiByteToWideChar.Ā Otherwise it's typically mbsrtowcs, but that's C++, not C and I'd have to look up the equivalent. Edit: It is a libc function in wchar.h.
1
u/_yrlf 4h ago edited 4h ago
the C standard library has rather lacking support for dealing with UTF-8 and Unicode in general. The standard
charandwchar_ttypes aren't even guaranteed to correspond to UTF-8 or UTF-16 coding units, and especially on platforms like windows, might be something completely different.There are some functions in the C standard library for dealing with this:
https://en.cppreference.com/c/string/multibyte
e.g.
int mblen(const char * str, size_t len)will tell you how many bytes the next character will be composed of. Whether this interprets the string as UTF-8 or some other encoding depends on the current locale. On Linux, this will generally be UTF-8 nowadays, but on Windows this could be different.EDIT: I'm not 100% sure this is correct. I just read that
mblen()just depends onmbtowc()and so if your compiler/locale uses UTF-16 aswchar_tencoding, for some wider unicode characters that need 3 or 4 bytes to encode in UTF-8, you might still not accurately get the info of how many bytes that character is. For good unicode support in C, you might need an external library like icu (https://icu.unicode.org/)1
u/Gold-Part4688 2h ago edited 1h ago
this is very very mystified. To do utf8 "properly" is a big job, sure. But if you have simple requirements, it's actually really simple and fun.
at the core, you need something that looks at the leading bytes, the pattern looks like this
spoilers below, you can figure this all out yourself. I did and i'm a beginner++. you just need to know about bitwise operators, really. I wanted to make this a spoiler... but i can't put a code block in a spoiler. so here's a dividing line
š¤·āāļø
excuse this being c3 lol (warning: different operator precedence!) But mostly it's that error handing, panicking with exit(1), or assuming all input is proper utf8 (which isn't an awful assumption) is up to you to implement. The simple way to use this, is just looping across the string, but advancing by a variable number of characters at a time, and doing something intelligent with them inside each iteration.
(I stole this idea from tsoding, who stole it from jai, who stole it from somewhere else utf8 video and here's one about string views in c, if you like. string view video . i think his way is also more proper than mine, and handles ALL invalid utf8 properly. the link at the top explains the flaws with this approach also)
then if you like, you can implement something like a utf8string type. c3 already has a string view (aka string slice, and slices) in the language, i'm just adding another nested field for that, along with functions to allocate, free, convert, iterate, and fill this thing. would be better to reimplement string, which i might do. the benefit of this layout is that casting to string works ^^ you may want to be able to cast to a null terminated string instead
of course there's many ways to implement this, you can also have an array of strings. array of pointers, array of string slices!. you can have a brand new printable or unprintable type that you create for utf8. world is your oyster. hell it can be a linked list. -- but you dont even have to do this, you can also just use byes_for_utf8() on every character you're dealing with.
then when you need something for production, you can grab a utf8 lib, knowing how it works. But this should be fun!
0
u/LaggerFromRussia 4h ago
In utf-8 continuation byte is encoded as 0b10xxxxxx, so you can skip total_char increment if character's two highest bits are equal to 0b10. It's enough to count codepoints, but to count graphemes you will need some library to work with unicode and utf-8.