将文件文本与 argvc 进行比较

Compare file text with argvc

我正在尝试从文件中读取字符(完成)并计算命令行参数显示的次数。当我使用下面的代码 运行 时,我的终端出现以下错误:“In file included from Fisier.c:3:0: /usr/include/string.h:144:12: 注意:应为“const char *”但参数类型为“char” extern int strcmp (const char *__s1, const char *__s2) "

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

int main(int argc, char *argv[]) {
    int c, nr = 0;
    char filename[30];
    char ch;
    char *ch2;
    strcpy(ch2, argv[2]);

    strcpy(filename, argv[1]);
    FILE *file;
    file = fopen(filename, "r");

    if (file) { 
        do {
            ch = fgetc(file);
            if (feof(file))
                break;
            char *pChar = malloc(sizeof(ch));
            strcpy(pChar[0], ch);   
            if (strcmp(ch2, pChar[0]))
                nr++;   
        } while(1);

        fclose(file);
    }
    printf("%d", nr); 
    return 0;
}

你的程序有几个问题:

  • 你在应该直接使用字符的地方使用了字符串函数。
  • 您使用 feof() 来测试文件结束,最好将文件字节读入 int 并与 EOF 进行比较。
  • 您将 argv[1] 复制到一个 30 字节的缓冲区中,命令行参数可以超过 29 个字节。直接用就行了

这是更正后的版本:

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

int main(int argc, char *argv[]) {
    int c, search, nr = 0;
    FILE *file;

    if (argc < 3) {
        printf("usage: %s file character\n", argv[0]);
        exit(1);
    }

    // set search as the character to count.
    //  it must be cast as unsigned char because getc(file) returns
    //  unsigned char values which may be different from char values
    //  if char is signed and the file contains non ASCII contents.
    search = (unsigned char)(*argv[2]);

    file = fopen(argv[1], "r");
    if (file) { 
        while ((c = getc(file)) != EOF) {
            if (c == search)
                nr++;
        }
        fclose(file);
    }
    printf("%d\n", nr); 
    return 0;
}