简体   繁体   English

使用C代码从文件读取字符

[英]reading characters from a file using c code

I have written a C code to count no of characters, words and lines in a file. 我写了一个C代码来计算文件中没有字符,单词和行数。
The code is as follows. 代码如下。

#include "stdio.h"
#include "conio.h"

#define FILE_NAME "abc.txt"

void main()
{
    FILE *fr;
    int noc = 0;
    int now = 0;
    int nol = 0;
    char ch;

    printf("hello world\n");
    getch();

    //clrscr();

    fr = fopen("..\\abc.txt","r");

    if(fr == NULL)
    {
        printf("\n error \n");
        getch();
        return;
    }

    ch = fgetc(fr);
    while(ch != EOF)
    {
        printf("%c", ch);
        noc++;
        if(ch == ' ');
        {
            now++;
        }
        if(ch=='\n')
        {
            nol++;
            now++;
        }
        ch=fgetc(fr);
    }

    fclose(fr);

    printf("\n noc = %d now = %d nol = %d\n", noc, now, nol);
    getch();
}

My file abc.txt is as follows. 我的文件abc.txt如下。

Hello my friend. 
How are you doing? 

I am getting following output: 我得到以下输出:

hello world
Hello my friend.
How are you doing?

 noc = 38 now = 40 nol = 2

The code is able to read no of characters and no of lines properly. 该代码能够正确读取任何字符和行。 However, it considers each character as a word. 但是,它将每个字符视为一个单词。 I am not understanding where am I going wrong when counting no of words in the code above. 当不计算上面代码中的单词数时,我不明白我在哪里出错。

Detailed explanations would be appreciated. 详细的解释将不胜感激。
Thanks in advance. 提前致谢。

if(ch == ' '); <------- see this (remove semicolon)
{
     now++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM