将文件文本与argvc进行比较

时间:2016-01-03 20:21:15

标签: c command-line-arguments argv

我正在尝试从文件中读取字符(已完成)并计算显示命令行中的参数的次数。当我从下面运行代码时,我的终端中出现以下错误:“在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;
}

1 个答案:

答案 0 :(得分:1)

你的程序有几个问题:

  • 你使用字符串函数,你应该直接使用字符。
  • 您使用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;
}