我正在尝试使用标准的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;
}
到目前为止,我在这段代码中遇到的问题是它仅计数一个字符(仅第一个字符),我想知道如何使其读取并计算在命令中写入的其他字符,谢谢提前:)
[您只计算一个字符argv [2] [0],即argv [2]是“ abcd”,那么您只在数“ a”。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct char_count {
char c;
int count;
};
static char read_char(FILE *file)
{
char c = 0;
fscanf(file, "%c", &c);
return c;
}
static void print_count(struct char_count *cc, int len)
{
int i;
for (i = 0; i < len; i ++) {
printf("%c-%d ", cc[i].c, cc[i].count);
}
printf("\n");
}
int main(int argc, char **argv)
{
FILE *file;
char c = 0;
struct char_count *cc;
int len = 0;
int i;
if (argc != 3)
return printf("Invalid arguments !\n");
file = fopen(argv[1], "r");
if (!file)
return printf("Could not open file !\n");
len = strlen(argv[2]);
if (len < 1)
return printf("At least one char required !\n");
cc = calloc(len, sizeof(struct char_count));
if (!cc) {
printf("Error allocation memory !\n");
return 1;
}
for (i = 0; i < len; i++) {
cc[i].c = argv[2][len - (i + 1)];
}
while(!feof(file)) {
c = read_char(file);
for (i = 0; i < len; i++) {
if (c == cc[i].c)
cc[i].count++;
}
}
printf("\n");
print_count(cc, len);
return 0;
}