【发布时间】:2020-09-10 14:32:32
【问题描述】:
我正在尝试使用标准 POSIX 函数编写一个接收文件和字符串的程序,程序计算字符串包含的文件中的所有字符。
例如,如果用户写:
count.exe x.txt abcd
程序计算文件x.txt中每个字符的个数:a,b,c,d
示例消息:
Number of 'a' characters in 'x.txt' file is: 4
Number of 'b' characters in 'x.txt' file is: 9
Number of 'c' characters in 'x.txt' file is: 7
Number of 'd' characters in 'x.txt' file is: 0
到目前为止我得到的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#define BUFSIZE 1024
void exit_sys(const char* msg)
{
perror(msg);
exit(EXIT_FAILURE);
}
void exit_fail(const char* msg)
{
fprintf(stderr, "%s\n", msg);
exit(EXIT_FAILURE);
}
int get_count(char* p, size_t size, char c)
{
int count = 0;
size_t i;
for (i = 0; i < size; ++i)
if (p[i] == c)
++count;
return count;
}
void run_count_characters_application(int argc, char** argv)
{
int fd;
char c;
char buf[BUFSIZE];
int n;
int count;
if (argc != 3)
exit_fail("usage: ./mycounter file character");
if (strlen(argv[2]) < 0)
exit_fail("You have to give at least one character");
c = argv[2][0];
if ((fd = open(argv[1], O_RDONLY)) < 0)
exit_sys("open");
count = 0;
while ((n = read(fd, buf, BUFSIZE)) > 0)
count += get_count(buf, n, c);
if (n < 0)
exit_sys("read");
printf("Count:%d\n", count);
close(fd);
}
int main(int argc, char** argv)
{
run_count_characters_application(argc, argv);
return 0;
}
到目前为止我在这段代码中得到的问题是它只计算一个字符(只计算第一个字符),我想知道如何让它读取并计算我在命令中写入的其他字符,谢谢你提前:)
【问题讨论】:
-
你正在做
c = argv[2][0];,它只传递c的ASCII值,而不是其余的字符 -
你必须保留几个计数器,一个用于参数字符串中的每个字符。您可以将它们存储在
unsigned int counter[UCHAR_MAX + 1]中,然后只更新和打印您感兴趣的那些(例如counter['a']++)。不过,这仅适用于 ascii 字符... -
@Inian 我该如何解决这个问题?
-
@MarcoLucidi 你能举例解释一下吗,因为我非常了解 C 语言,但我并不完全理解如何去做。