用于计算文件中的行,字符或单词的程序

时间:2018-04-03 03:13:43

标签: c

我正在编写一个计算单词作为练习的程序,但是我遇到了一个问题,即无论选择哪个选项,都会错误计算。

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

int main(int argc, char **argv){
    int totalcount = 0; //hold overall count
    for(int i = 2; i < argc; i++){
        int count = 0; //hold count for each file
        int c; //temporarily hold char from file 
        FILE *file = fopen(argv[i], "r");

            if (strcmp("-c",argv[1])){
                while((c = fgetc(file)) != EOF){
                    count++;
                }
            }
            else if(strcmp("-w",argv[1])){
                bool toggle = false; //keeps track whether the next space or     line indicates a word
                while((c = fgetc(file)) != EOF){
                    if(!toggle && ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))){
                        toggle = true;
                    }
                    if(toggle && ((c == '\n') || (c == ' '))){
                        count++;
                        toggle = false; 
                    }
                }
            }
            else{
                while((c = fgetc(file)) != EOF){
                    if(c == '\n'){
                        count++;
                }
            }
        }
        printf("%d %s", count, argv[i]);
        fclose(file);
        totalcount += count;
    }
    if (argc > 3){
        printf("%d total", totalcount);
    }

    return 0;
}

我不知道为什么我的char计数逻辑不起作用。在编写每个部分时,我已经完成了我的逻辑,但它对我来说没有意义,为什么它不会让我工作。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

当字符串相等时,

strcmp返回0,所以永远不要进入if/else statement

if (strcmp("-c",argv[1]) == 0){ //return value is 0
    while((c = fgetc(file)) != EOF){
        count++;
    }
}
else if(strcmp("-w",argv[1]) == 0){ //return value is 0
    bool toggle = false; //keeps track whether the next space or     line indicates a word
    while((c = fgetc(file)) != EOF){
        if(!toggle && ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))){
            toggle = true;
        }
        if(toggle && ((c == '\n') || (c == ' '))){
            count++;
            toggle = false; 
        }
    }
}

希望它适合你

答案 1 :(得分:0)

您可以逐行阅读文件,它可以简化任务

int get_lines_chars(const char *path)
{
    /* Open templorary file */
    FILE *fp = fopen(path, "r");
    if (fp != NULL) 
    {
        ssize_t read;
        size_t len = 0;
        char *line = NULL;
        unsigned int line_no, char_no;
        line_no = char_no = 0;

        /* Read line-by-line */
        while ((read = getline(&line, &len, fp)) != -1) 
        {
            int curr_line = 0;
            while (*line)
            {
                curr_line++;
                char_no++;
                line++;
            }

            line -= curr_line;
            line_no++;
        }

        /* Cleanup */
        fclose(fp);
        if(line) free(line);

        printf("File has %d lines and %d chars\n", line_no, char_no);
        return 1;
    }

    return 0;
}