c - 查找文本文件中的字符数、单词数和行数

标签 c file text

这是 .c 文件,后面是我的 .h 文件中的函数

#include <stdio.h>
#include "functions.h"
#define INPUT_FILE "C:/Users/user/Desktop/test.txt"






int main(){
    FILE *text_file;
    int num_characters, num_words, num_lines;


    text_file = fopen(INPUT_FILE,"r");

    if(text_file == NULL){
        printf("!!-------ERROR OPENING FILE------!!\nclosing program....");
        return 0;
    }

    num_characters = read_characters(text_file);
    num_words = read_words(text_file);
    num_lines = read_lines(text_file);

    printf("Number of Characters: %d\nNumber of Words: %d\nNumber of Lines: %d\n",num_characters,num_words,num_lines);


    return 0;
}


#include <stdio.h>
#include "functions.h"
#define INPUT_FILE "C:/Users/Lott-kerby/Desktop/test.txt"





#ifndef FUNCTIONS_H_
#define FUNCTIONS_H_
#include <stdio.h>


int read_characters(FILE *text_file){
    int i;
    int char_count = 0;
    while((i = fgetc(text_file)) !=EOF)
        char_count++;


    return char_count;
}


int read_words(FILE *text_file){
    char j;
    int word_count = 0;
    while((j = fgetc(text_file)) != EOF){
        if(j == ' ')
            word_count++;
    }
    return word_count;
}

int read_lines(FILE *text_file){
    char k;
    int line_count = 0;
    while((k = fgetc(text_file)) != EOF){
        if(k == '\n')
            line_count++;
    }
    return line_count;
}

目标是找出文本文件中的字符数和行数。我在运行时得到了正确的字符数,但得到的单词和行数不正确。我使用的文本文件如下:

word
word
word

有了这个 .txt,我的程序输出是: 字数:14 字数:0 行数:0

任何帮助将不胜感激。 “单词”在我的文本文件中各占一行。

最佳答案

好吧,你通过计算空格的数量来计算单词的数量,因为你假设每个单词之间都有一个空格。但在您的示例输入文件中没有空格。

因此您可能想要添加一个空格或换行检查。

您可能还想返回 word_count+1 和 line_count+1,因为没有换行符的单行应该返回 1。对于没有空格的单个单词也是如此

编辑:哦,现在我看到您多次读取文件而没有重置文件指针,因此 fgetc 将始终立即在 read_words() 和 read_lines() 中返回 EOF ... 重置它使用

rewind ( text_file );

关于c - 查找文本文件中的字符数、单词数和行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31372871/

相关文章:

c - for循环不运行

c++ - 错误 : expected '=' , ','、 ';'、 'asm' 或 '__attribute__' token 之前的 ':'

c - sizeof C 中的整数表达式

ios - 使用在后台运行的应用程序打开文件

c++ - 倒回文件是否比关闭文件并再次打开它更有效?

c++ - dlopen 或 dlclose 未调用信号处理程序

python - 多项选择题的干扰因素生成

excel - matlab,如何将文本和数值数据导出到 excel csv 文件?

c++ - 文本相似度算法/库

C,使用 argv[] 作为命令行参数