C 查找输入文本文件中最常用的字符

C 查找输入文本文件中最常用的字符,c,C,我试图从命令行读取一个输入txt文件,并在该文件中查找学校项目中最常用的字符。我可以用下面的代码打开txt文件并打印它,而不会出现问题。另外,当我从命令行给它一个字符串时,freqcount()下面的函数也能很好地工作。但我似乎无法让他们一起工作。我想我在下面设置dest数组时弄乱了一些东西。任何帮助都将不胜感激 另外,对于非静态大小的字符串,通常使用哪一个更好,malloc还是calloc #include <stdio.h> #include <stdlib.h> #

我试图从命令行读取一个输入txt文件,并在该文件中查找学校项目中最常用的字符。我可以用下面的代码打开txt文件并打印它,而不会出现问题。另外,当我从命令行给它一个字符串时,freqcount()下面的函数也能很好地工作。但我似乎无法让他们一起工作。我想我在下面设置dest数组时弄乱了一些东西。任何帮助都将不胜感激

另外,对于非静态大小的字符串,通常使用哪一个更好,
malloc
还是
calloc

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <string.h>

#define DEST_SIZE 26 // An arbitrary size but longest string to work is 24

char freqcount(char * str){

    // Construct character count array from the input 
    // string. 
    int len = strlen(str); 
    int max = 0;  // Initialize max count 
    char result;   // Initialize result 
    int count[255] = {0};

    // Traversing through the string and maintaining 
    // the count of each character 
    for (int i = 0; i < len; i++) { 
        count[str[i]]++; 
        if (max < count[str[i]]) { 
            max = count[str[i]]; 
            result = str[i]; 
        } 
    } 

    return result; 
}

//////////////////////////////////////////////////////////////////////

int main(int argc,char ** argv){
    int i=0;
    char dest[DEST_SIZE] = {0};

    if(argc !=2){
        perror("Error: ");
        return -1;
    }

    FILE * f = fopen(argv[1], "r");
    if (f == NULL) {
        return -1;
    }
    int c;

    while ( (c=fgetc(f)) != EOF && i++<DEST_SIZE ) {
        printf("%c",c);
        dest[i]=c;
        char cnt=freqcount(dest);
        printf("%c",cnt);
    }

    return EXIT_SUCCESS;
}

将调用
freqcount
移动到while循环之后:

while ( (c=fgetc(f)) != EOF && i++<DEST_SIZE ) {
    printf("%c",c);
    dest[i]=c;
}
dest[i]='\0';    // terminate
char cnt=freqcount(dest);
printf("%c",cnt);

while((c=fgetc(f))!=EOF&&i++将调用
freqcount
移动到while循环之后:

while ( (c=fgetc(f)) != EOF && i++<DEST_SIZE ) {
    printf("%c",c);
    dest[i]=c;
}
dest[i]='\0';    // terminate
char cnt=freqcount(dest);
printf("%c",cnt);

while((c=fgetc(f))!=EOF&&i++它将
(null)
返回给函数callYes,它将这样做:
printf(“%s”,cnt);
但是
cnt
不是字符串。使用
%c
。根据我的示例,您必须终止
dest
。它将
(null)
返回给函数callYes,它将这样做:
printf(“%s”,cnt);
cnt
不是字符串。请使用
%c
。您必须按照我的示例终止
dest
while ( (c=fgetc(f)) != EOF && i++<DEST_SIZE ) {
    printf("%c",c);
    dest[i]=c;
}
dest[i]='\0';    // terminate
char cnt=freqcount(dest);
printf("%c",cnt);