我正在尝试编写一个使用标准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 <unistd.h>
#define BUFSIZE 1024
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)
printf("usage: ./mycounter file character");
//if (strlen(argv[2]) != 1)
printf("You have to give at least one character");
c = argv[2][0];
if ((fd = open(argv[1], O_RDONLY)) < 0)
printf("open");
count = 0;
while ((n = read(fd, buf, BUFSIZE)) > 0)
count += get_count(buf, n, c);
if (n < 0)
printf("read");
printf("Count:%d\n", count);
close(fd);
}
int main(int argc, char** argv)
{
run_count_characters_application(argc, argv);
return 0;
}
到目前为止,我在这段代码中遇到的问题是它仅计数一个字符(仅第一个字符),我想知道如何使其读取并计算在命令中写入的其他字符,在此先感谢您:)