我的节目计数字母,但它确实算不错。它应该计算文件中每一行的字母数量。 源代码:
FILE *fp;
int i,
counter; // Liczba liter w wiadomosci
setlocale(LC_ALL, "pl_PL.UTF-8");
while(run)
{
fp = fopen(FIFO, "r");
fwide(fp, 1);
while ((line = fgetws(buffer, sizeof buffer / sizeof buffer[0], fp)) != NULL)
{
counter = 0;
for (i = 0; line[i] != L'\0'; i++)
if (iswalpha(line[i]))
counter++;
printf("Amount of letters: %d", counter);
}
fclose(fp);
}
当在文件中是'\ 0'行的特定符号末尾时,它没有正确计数。例如,如果文件我得到行:qwerty \ 00 azerty并且它仅返回6而不是12的数量。 我该如何解决?
答案 0 :(得分:0)
使用read(3)
(或fread(3)
)
size_t nread = fread(buffer, sizeof(buffer) / sizeof(*buffer), sizeof(*buffer), fp);
然后,假设您想要逐行编号:
for (wchar_t *bp = buffer, *ep = buffer + nread; bp < ep; bp++) {
/* look for end-of-line character */
wchar_t *eol = wmemchr(bp, L'\n', ep - bp);
size_t n;
if (eol == NULL) {
/* now what? count the characters till the end of the buffer? */
...
}
/* the subarray from BP to EOL is one line, do the counting */
n = count(bp, eol - bp);
printf("Amount of letters: %zu\n", n);
/* set bp to eol for the next iteration */
bp = eol;
}
所有计数代码现在都在:
size_t count(const wchar_t *line, size_t ncharacters)
{
size_t counter = 0;
for (size_t i = 0; i < ncharacters; i++) {
if (iswalpha(line[i])) {
counter++;
}
}
return counter;
}
当然这些代码缺少错误检查,就像eol
为NULL时一样,因为缓冲区中没有任何换行符。此外,您可能必须遍历fread(3)
位,因为fread(3)
可能返回的项目少于您的缓冲区可以解释的项目,例如因为非阻塞I / O或仅仅因为没有更多目前可用的角色。