查找文本文件中的字符数,单词和行数

时间:2015-07-12 21:39:54

标签: 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 NUmber的话:0 行数:0

任何帮助将不胜感激。 “单词”在我的文本文件中各自独立。

1 个答案:

答案 0 :(得分:1)

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

所以你可能想要添加一个空格或新行的检查。

此外,您可能希望返回word_count + 1和line_count + 1,因为没有换行符的单行应返回1.对于没有空格的单个单词也是如此

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

rewind ( text_file );
相关问题