计算文件中字符数、单词数和行数的C代码

标签 c file

我是 C 的初学者,所以我想看看一个代码,它包括计算给定文件中的字符数、单词数和行数。我发现了下面的代码,但问题是我不明白为什么我们必须在 while 循环之后增加最后一个单词的单词和行:if (characters > 0)...

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

int main() {
    FILE *file;
    char path[100];
    char ch;
    int characters, words, lines;

    /* Input path of files to merge to third file */
    printf("Enter source file path: ");
    scanf("%s", path);

    /* Open source files in 'r' mode */
    file = fopen(path, "r");

    /* Check if file opened successfully */
    if (file == NULL) {
        printf("\nUnable to open file.\n");
        printf("Please check if file exists and you have read privilege.\n");
        exit(EXIT_FAILURE);
    }

    /*
     * Logic to count characters, words and lines.
     */
    characters = words = lines = 0;
    while ((ch = fgetc(file)) != EOF) {
        characters++;

        /* Check new line */
        if (ch == '\n' || ch == '\0')
            lines++;

        /* Check words */
        if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
            words++;
    }

    /* Increment words and lines for last word */
    if (characters > 0) {
        words++;
        lines++;
    }

    /* Print file statistics */
    printf("\n");
    printf("Total characters = %d\n", characters);
    printf("Total words      = %d\n", words);
    printf("Total lines      = %d\n", lines);

    /* Close files to release resources */
    fclose(file);

    return 0;
}

最佳答案

这个程序有一些问题:

  • ch 必须定义为 int 以允许正确检测 EOF

  • scanf("%s", path); 的输入过长将导致 path 溢出并导致未定义的行为。还要检查返回值以检测无效输入或文件过早结束:

    if (scanf("%99s", path) != 1)
        return 1;
    
  • 测试 ch == '\0' 来计算行数是有争议的。标准 wc unix 实用程序不会将空字节视为行分隔符。

  • if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0') 也是不是检测单词边界的标准方法。 if (isspace(ch)) 更加地道。

  • 字数不正确:多个空格将被视为多个字!您应该改为检测边界,即空格字符后跟非空格字符。

  • 最后的测试是解决上述问题的蹩脚尝试,它还不够。如果流不以换行符结束,则确实需要额外的测试来计算流的最后一个。

这是一个更正的版本:

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

int main() {
    FILE *file;
    char path[1024];
    int ch, last;
    long long int characters, words, lines;

    /* Input path of files to merge to third file */
    printf("Enter source file path: ");
    if (scanf("%255s", path) != 1) {
        printf("Invalid input\n");
        return EXIT_FAILURE;
    }

    /* Open source files in 'r' mode */
    file = fopen(path, "r");

    /* Check if file opened successfully */
    if (file == NULL) {
        printf("Unable to open file %s\n", path);
        printf("Please check if file exists and you have read privilege.\n");
        return EXIT_FAILURE;
    }

    /*
     * Logic to count characters, words and lines.
     */
    characters = words = lines = 0;
    last = '\n';
    while ((ch = fgetc(file)) != EOF) {
        characters++;

        /* Check new line */
        if (ch == '\n')
            lines++;

        /* Check words */
        if (!isspace(ch) && isspace(last))
            words++;

        last = ch;
    }

    /* Increment words and lines for last word */
    if (last != '\n') {
        lines++;
    }

    /* Print file statistics */
    printf("\n");
    printf("Total characters = %lld\n", characters);
    printf("Total words      = %lld\n", words);
    printf("Total lines      = %lld\n", lines);

    /* Close file to release resources */
    fclose(file);

    return 0;
}

关于计算文件中字符数、单词数和行数的C代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54845010/

相关文章:

c - 伪代码中的红黑树插入和修复有问题

c - 如何使用 Swift 返回 UnsafePointer <CChar> 和 UnsafePointer <CUnsignedInt>

c - 如何以编程方式查找计算机的套接字等待队列大小?

c++ - 循环遍历 CAF 文件的示例

azure - 当 Azure DevOps 管道模板驻留在独立存储库中时,是否可以引用这些模板内的文件?

javascript - 文件类型可记录的属性,但在尝试从原型(prototype)函数访问所述属性时返回未定义

linux - 如何在不重新安装/删除文件的情况下修复/恢复 Linux 权限?

python - 如何使用 C Python API 从 C 注入(inject) Python 中的可捕获异常?

c# - 使用我的 C# 应用程序打开特定文件——例如使用 Word 打开 .doc 文件

perl - 将文件句柄与 IO::Select::can_read() 返回的 glob 进行比较