📌  相关文章
📜  国际空间研究组织 | ISRO CS 2008 |问题 57(1)

📅  最后修改于: 2023-12-03 15:07:33.435000             🧑  作者: Mango

ISRO CS 2008 Question 57

This question was asked in the ISRO CS 2008 exam. It is a programming question and a sample solution is shown below.

Problem statement

Write a program in C language that counts the number of lines, words, and characters in a text file. The file name should be supplied as a command-line argument.

Solution
#include <stdio.h>

int main(int argc, char *argv[]) {
    FILE *fp;
    char ch, prev;
    int lines = 0, words = 0, chars = 0;

    if (argc != 2) {
        printf("Usage: %s <file name>\n", argv[0]);
        return 1;
    }

    fp = fopen(argv[1], "r");

    if (fp == NULL) {
        printf("Cannot open file '%s'\n", argv[1]);
        return 2;
    }

    prev = ' ';
    while ((ch = getc(fp)) != EOF) {
        chars++;
        if (ch == '\n') {
            lines++;
        }
        if (ch == ' ' || ch == '\n' || ch == '\t') {
            if (prev != ' ' && prev != '\n' && prev != '\t') {
                words++;
            }
        }
        prev = ch;
    }

    if (prev != ' ' && prev != '\n' && prev != '\t') {
        words++;
    }

    printf("Lines: %d\nWords: %d\nCharacters: %d\n", lines, words, chars);

    fclose(fp);

    return 0;
}
Explanation

The main function takes two arguments: argc, the argument count, and argv, an array of strings, which contains the command-line arguments. We check that the argument count is exactly 2, and print an error message and return an error code if it isn't.

We attempt to open the file specified by the command-line argument using fopen. If the file cannot be opened, we print an error message and return an error code.

We then loop through the file character by character using getc. For each character, we increment a character counter chars. If the character is a newline character (\n), we increment a line counter lines. If the character is a whitespace character ( ), a newline character, or a tab character (\t), we check if the previous character was not a whitespace character, newline character, or a tab character. If it wasn't, we increment a word counter words. We store the current character in a variable prev to remember it for the next iteration.

After the loop, we check if the last character was not a whitespace character, newline character, or tab character, and increment the word counter words if it wasn't.

Finally, we print the line count, word count, and character count, and close the file using fclose.