r/C_Programming • • 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

17 comments sorted by

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.

3

u/Rararror 4h ago

nah... just some bit masking

6

u/Dazzling_Music_2411 4h ago edited 4h ago

For a beginner like OP, who states that "everything that I read online is too complex" I wonder if bit masking wouldn't border on "dauntingly difficult".

PS.

Maybe I exaggerated a bit, I've never tried it myself, but I can't help wondering if that approach is a recipe for disaster, especially when there are established easy ways to tackle the problem.

But maybe it's just a fun programming kata.
I'd love to see your "pretty simple solution" to OP's request.

2

u/MoistAttitude 4h ago

It's not that hard.

Bytes matching 110x-xxxx mean a two-byte code, 1110-xxxx mean a three byte and so on. Bytes matching 10xx-xxxx are the additional bytes. The x's in those will make the character code.

Here's a more in depth description.

1

u/Dazzling_Music_2411 4h ago

Thanks. I was actually just reading that! Easier than I thought it might be.

2

u/Dazzling_Music_2411 4h ago

Actually, reading over the UTF-8 spec I think you may be right! šŸ˜‰

(Sorry for doubting!) šŸ˜‚

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 compiler char can be signed or unsigned. I'd recommend declaring it explicitly as unsigned char to avoid portability pitfalls.

1

u/lassehp 3h ago

Great Scott! "Erroring" on bytes above 0x7f...That was as stupid idea even back in the beginning of the nineties, when the ISO 8859-1 Latin 1 character set became common. Some stupid software would either delete non-7-bit ASCII bytes, or mask off the 8th bit with c&0x7f, or something similar idiotic. Fortunately many programs just did the lazy thing - nothing - which was also the right thing, including a lot of Internet software.

Unicode is smart. If you don't want to discern between letters and punctuation, but just count characters rather than bytes, just count the first byte of a UTF-8 multibyte sequence, and skip the following continuation bytes.Ā 

1

u/hgs3 2h ago

just count the first byte of a UTF-8 multibyte sequence, and skip the following continuation bytes

Be careful! Malformed UTF-8 is a thing, and if the final sequence of a string is truncated, you risk advancing past the null terminator. Fortunately OP isn't dealing with strings and fread won't read past EOF.

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 char and wchar_t types 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 on mbtowc() and so if your compiler/locale uses UTF-16 as wchar_t encoding, 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

// https://www.omarpolo.com/post/parsing-utf8.html (link is amazing)
// one byte:       0.......
// two bytes:      110..... 10......
// three bytes:    1110.... 10...... 10......
// four bytes:     11110... 10...... 10...... 10......

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


šŸ¤·ā€ā™€ļø


 fn Len? bytes_for_utf8(char c)
{
	if (c & 0b1000_0000 == 0) // ascii
	{
		return 1;
	}
	if (c & 0b1100_0000 == 0b1000_0000) // invalid
	{
		return string::INVALID_UTF8~;
	}
	if (c & 0b1110_0000 == 0b1100_0000) // 2 bytes
	{
		return 2;
	}
	if (c & 0b1111_0000 == 0b1110_0000) // 3 bytes
	{
		return 3;
	}
	if (c & 0b1111_0000 == 0b1111_0000) // 4 bytes
	{
		return 4;
	}
	return string::INVALID_UTF8~;
  }

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

 struct UString
 {
	String string;
	Len[] lens;
 }
 alias Len = ichar;

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.