Best way to convert whole file to lowercase in C

后端 未结 5 1572
死守一世寂寞
死守一世寂寞 2021-01-21 10:06

I was wondering if theres a realy good (performant) solution how to Convert a whole file to lower Case in C. I use fgetc convert the char to lower case and write it in another t

5条回答
  •  臣服心动
    2021-01-21 10:31

    Well, you can definitely speed this up a lot, if you know what the character encoding is. Since you're using Linux and C, I'm going to go out on a limb here and assume that you're using ASCII.

    In ASCII, we know A-Z and a-z are contiguous and always 32 apart. So, what we can do is ignore the safety checks and locale checks of the toLower() function and do something like this:

    (pseudo code) foreach (int) char c in the file: c -= 32.

    Or, if there may be upper and lowercase letters, do a check like if (c > 64 && c < 91) // the upper case ASCII range then do the subtract and write it out to the file.

    Also, batch writes are faster, so I would suggest first writing to an array, then all at once writing the contents of the array to the file.

    This should be considerable faster.

提交回复
热议问题